This compiles fine on GCC 8.2:
class M
{
public:
    const Pointer* getPointer() const {return _ptr;}
private:
    Pointer* _ptr{nullptr};
};
but when I add another const to the function:
class M
{
public:
    const Pointer* const getPointer() const {return _ptr;}
private:
    Pointer* _ptr{nullptr};
};
I get the compiler error:
error: type qualifiers ignored on function return type [-Werror=ignored-qualifiers]
Why would it not let me add additional const-ness? Since when was extra const bad?
Because returning a const something by value like here makes no difference with or without.
For example:
const int GetMyInt()
{
  int k = 42;
  return k;
}
//later..
int ret = GetMyInt();
// modify ret.
Because the returned value from GetMyInt will be copied into ret anyway (not taking (N)RVO into account), having GetMyInt return const makes no difference.
Normally this is a warning because it's superfluous code but -Werror turns every warning into an error so there's that.
The const qualifier has no effect in this position, since the returned value is a prvalue of non-class type and therefore cannot be modified anyway.
Notice that the compiler message says -Werror=, meaning that it's normally a warning (so the code is not wrong, but warning-worthy). It has been turned into an error by your compilation settings.
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