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
opt
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.
Returning a constant value only makes sense when you return a reference or a pointer(in this case pointer to constant and not a constant pointer) because the caller is able to modify the referenced (pointed to) value.
Another comment on the code not related to your question: I think it's better to use a setter instead of
int& getNonconstReference() {
return _myInt;
}
Which will should be:
void setMyInt(int n) {
_myInt = n;
}
Moreover, it's useless to return a const reference to an int. It does make sense for a bigger object whose copy or move is more expensive.
Having this
struct Foo { Foo(int) {} operator bool() { return true; } };
and that
Foo some_calculation(int a, int b) { Foo result(a + b); /*...*/ return result; }
the example
if (some_calculation(3, 20) = 40) { /*...*/ }
compiles without a warning. Of course, this is rare. But isn't const correctness about making it hard for people to do things wrong? And with the expectation that people try things, that are wrong, the return type should be declared const. And: g++ warns about ignoring the classifier, but does not ignore it. I think, the warning is about users that take the copy and ignore the const classifiers on their copy. But that should not be a warning, because this is absolutely correct behavior. And it makes sense to do this.
Shouldn't -pedantic only allow strict adherence to the ISO standard? Depending on -std= of course...
This warning is also useful to avoid confusion when declaring functions returning pointers to objects which should not be modified:
// "warning: type qualifiers ignored on function return type"
// as the pointer is copied.
Foo* const bar();
// correct:
const Foo* bar();
Scott Meyers pointed out that there's pretty good reason why someone would want to return const
values. Here's an example:
int some_calculation(int a, int b) { int res = 0; /* ... */ return res; }
/* Test if the result of the calculation equals 40.*/
if (some_calculation(3,20) = 40)
{
}
Do you see what I did wrong? This code is absolutely correct and should compile. The problem is that the compiler didn't understand that you intended tocompare instead of assign the value 40
.
With a const
return value the above example won't compile. Well, at least if the compiler doesn't discard the const
keyword.