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.
Why do you care if the pointer is changed? Doing this is like saying:
The value returned by f() is a copy - changing it changes nothing, so there is nom point in making it const.
Why return a const value? Consider the following (and please excuse the unimaginative variable names):
Given that declaration of
operator+
, I can do the following:That's right, I just assigned to the temporary
A
that was returned byoperator+
. The resulting value ofd.a
is 4, not 5. Changing the return type ofoperator+
toconst A
prevents this assignment, causing the expression(a+b) = c
to generate a compiler error.If I try to assign to a pointer or integer returned from a function, my compiler (MSVC) generates a "left operand must be l-value" error, which seems consistent with the ARM compiler telling you that the constness of the pointer is meaningless--the pointer can't be assigned to anyway. But for classes/structs, apparently it's okay to assign to non-const return values.
the const qualifier doesn't mean anything because you're returning a pointer
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:
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.
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:
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.
One simple way of making sure you're defining the return type you want is to always add modifiers on the right (as opposed to left) side of original type.
That should help make sure your return types are never meaningless again :)