A few months back, I wrote about wanting a warning from C++, and not being able to get one. It happened again.

We have code like this:

class CMyString
{
    /** Return a copy of the string with outlying spaces removed. */
    CMyString Trim() const;
};

If you read the comments and signature of the Trim() method, you see that it returns a copy of the string. But if you are less careful, you can think that this method trims the string in place:

CMyString fooey("  this needs trimming.   ");

fooey.Trim();                       // bad
CMyString good = fooey.Trim();      // good

I figured, there ought to be a way to get a compiler warning: not only is the return value ignored, but the method is declared const, so it conceptually has no side effects. I know: the const aspect can be worked around, but still, why can't the compiler warn me about this?

There's a warning that can tell me that I've used an enumeration type in a switch, and have not provided a case for every enumeration value. This warning will appear even if there is a default clause! If this is something that can be warned about, why not ignoring the return from a const method?

tagged: » 2 reactions

Comments

[gravatar]
Kartik 12:04 PM on 9 Apr 2004

Good catch. Regarding const methods having no side-effects, that could change if the object has data members declared with "mutable" keyword.

It would be worthwhile to see how other popular C++ compilers would behave with this code. It might also be worthwhile to use PC-Lint and see if it catches the snag.

I am wondering as developers could we somehow generate a compile-time assert to catch this problem?

[gravatar]
James Antill 12:41 PM on 12 Apr 2004

Well, assuming gcc you can do...

char *foo_dup(const char *)
__attribute__ ((__nonnull__))
__attribute__ ((__malloc__))
__attribute__ ((__warn_unused_result__));

...which says that you can't pass in a NULL ptr, and that the return value is allocated (opt: can't alias with anything) and a warning should be generated if the return value is ignored.

Add a comment:

name
email
Ignore this:
not displayed and no spam.
Leave this empty:
www
not searched.
 
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.