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
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.
There is a difference between const
on a basic type result, where it's ignored, and const
on a class type result, where it generally wreaks havoc.
namespace i {
auto f() -> int const { return 42; }
void g( int&& ) {}
}
namespace s {
struct S {};
auto f() -> S const { return {}; }
auto g( S&& ) {}
}
auto main() -> int
{
{ using namespace i; g( f() ); } // OK
{ using namespace s; g( f() ); } // !The `const` prevents this.
}
This is why the compiler warns in the first case: it's a special case, that may not do what one naïvely could expect.
For modern programming it would IMHO be nice also with a warning about const
on class type result, since it prohibits move semantics; a rather severe cost for whatever little advantage one envisioned.