c++pointersconstants

Const confusion in C++


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).


Solution

  • 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:

    double* &foo()
    {
        static double bar = 3.14;
        double *barP = &bar;
        return barP;
    }
    
    double myDouble;
    foo() = &myDouble;
    

    But this would not be possible:

    double* const &foo()
    {
        static double bar = 3.14;
        double *barP = &bar;
        return barP;
    }
    
    double myDouble;
    foo() = &myDouble; // error!
    

    Adding const to the return value (as to quality the pointer as const, not the pointed to data as const) in your case does nothing. If anything, your compiler should warn you about this, because really there's no different if you just remove the const qualifier (barring possible ABI changes, though I'm not sure if the standard allows for ABI changes in this case).