Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my return type meaningless?

I am trying to use a return type of const MyClass * const. However, I get a warning:

Warning: #815-D: type qualifier on return type is meaningless.

Is this not a valid type? I want a pointer than cannot be changed, and I want the thing it points to to not be changed either.

like image 715
Dynite Avatar asked Mar 26 '09 16:03

Dynite


2 Answers

The pointer itself has value type, so it doesn't make sense to make it const. What the caller function does with the returned value can't be restricted by the called function. This is akin to trying to define something like:

const int getInt();

getInt(), in this case, just returns an int value (not a reference). It goes to a register, then the caller function receives it and does whatever it wants with it.

like image 74
Juliano Avatar answered Sep 23 '22 06:09

Juliano


I agree with Juliano's answer, you want the constness of the pointer to be at the call site.

A better way to do what you are looking for is to have your function return a const reference to the object:

const MyClass& getMyClass()
{ 
  return myClass;
}

By definition references can't be modified, so you'd be better off.

Of course this won't work if your function is attempting to create a MyClass object. In that case you can just move the extra const to the call site.

// function definition
const MyClass* createMyClass()
{ 
  return new MyClass("I Love C++");
}

// use of a const pointer to a MyClass which is const
const MyClass* const myClassInstance = creatMyClass();
like image 45
Nick Haddad Avatar answered Sep 25 '22 06:09

Nick Haddad