lousybyte lousybyte - 9 months ago 53
C++ Question

Pointer to reference to const null value

This is the code:

const int x = 0;
const int& r = x;

const int* p1 = x; // Works (p1 = 0)
const int* p2 = r; // error C2440: 'initializing': cannot convert from 'const int' to 'const int *'

Why is p1 set to the value of x, but p2 not?

Is it because p2 cannot guarantee that x is const just by looking at r?

Or is there anything else subtle about references that causes this error?

Answer Source

The third line should provoke an error. It doesn't in VS2015. It's a bug in that compiler. Other compilers do emit error messages about this line.

Until C++11, any integral constant expression that evaluates to 0 is treated as a null pointer constant, so the first line is equivalent to const int* p1 = NULL;, It doesn't make p1 point to x.

Since C++11 (and VS2015 is supposed to support C++11) this is no longer the case. Roughly speaking, only literal zero and nullptr are valid null pointer constants.

The fourth line was never valid in any version of C++, because the type of r is a reference, not an integer.