Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra constness causes compiler error

Tags:

c++

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?

like image 747
user997112 Avatar asked May 31 '19 13:05

user997112


2 Answers

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.

like image 86
Hatted Rooster Avatar answered Oct 09 '22 07:10

Hatted Rooster


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.

like image 21
Angew is no longer proud of SO Avatar answered Oct 09 '22 07:10

Angew is no longer proud of SO