When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra
options) I suddenly got a bunch of errors of the form warning: type qualifiers ignored on function return type
.
Consider temp.cpp
:
class Something { public: const int getConstThing() const { return _cMyInt; } const int getNonconstThing() const { return _myInt; } const int& getConstReference() const { return _myInt; } int& getNonconstReference() { return _myInt; } void setInt(const int newValue) { _myInt = newValue; } Something() : _cMyInt( 3 ) { _myInt = 2; } private: const int _cMyInt; int _myInt; };
Running g++ temp.cpp -Wextra -c -o blah.o
:
temp.cpp:4: warning: type qualifiers ignored on function return type temp.cpp:7: warning: type qualifiers ignored on function return type
Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading const
is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const?
It doesn't violate the standard. That's why they're warnings and not errors.
And indeed you're right — the leading const
is superfluous. The compiler warns you because you've added code that in other circumstances might mean something, but in this circumstance means nothing, and it wants to make sure you won't be disappointed later when your return values turn out to be modifiable after all.
I encountered this warning when compiling some code that uses Boost.ProgramOptions. I use -Werror
so the warning was killing my build, but because the source of the warning was in the depths of Boost I couldn't get rid of it by modifying my code.
After much digging I found the compiler option that disables the warning:
-Wno-ignored-qualifiers
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With