Possible Duplicate:
Why is my return type meaningless?
Hi, I’m confused about a particular const conversion. I have something like
// Returns a pointer that cannot be modified,
// although the value it points to can be modified.
double* const foo()
{
static double bar = 3.14;
return &bar;
}
int main()
{
double* const x = foo(); // fine
const double* y = foo(); // eh?!
return 0;
}
When I compile this on MSVS 2008 (Express) there is no error, but it seems to me like there should be. The meaning behind x and y are quite different, so it does not seem like there should be this implicit conversion. So is this an issue with the compiler (unlikely), or my understanding of the const-ness involved here (quite likely).
The return value cannot be modified. That is, the pointer cannot be modified. However, because at the call site, the return value is an rvalue (without a defined
=operator), it cannot be modified anyway.If the return value was an lvalue (e.g. a reference), this would be possible:
But this would not be possible:
Adding
constto the return value (as to quality the pointer asconst, not the pointed to data asconst) in your case does nothing. If anything, your compiler should warn you about this, because really there’s no different if you just remove theconstqualifier (barring possible ABI changes, though I’m not sure if the standard allows for ABI changes in this case).