![]() | Ned Batchelder : Blog | Code | Text | Site Warning on ignored return? » Home : Blog : April 2004 |
Warning on ignored return?Wednesday 7 April 2004 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 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. "); 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:
c++» 2 reactions | |
Comments
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?
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: