Wednesday 7 April 2004 — This is close to 21 years old. Be careful.
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?
Comments
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?
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: