Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pedantic gcc warning: type qualifiers on function return type

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?

like image 207
Seth Johnson Avatar asked Jul 15 '09 21:07

Seth Johnson


2 Answers

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.

like image 192
Rob Kennedy Avatar answered Sep 26 '22 00:09

Rob Kennedy


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.

like image 24
ccaughie Avatar answered Sep 24 '22 00:09

ccaughie