The standard says that dereferencing the null pointer leads to undefined behaviour. But what is "the null pointer"? In the following code, what we call "the null pointer":
struct X
{
static X* get() { return reinterpret_cast<X*>(1); }
void f() { }
};
int main()
{
X* x = 0;
(*x).f(); // the null pointer? (1)
x = X::get();
(*x).f(); // the null pointer? (2)
x = reinterpret_cast<X*>( X::get() - X::get() );
(*x).f(); // the null pointer? (3)
(*(X*)0).f(); // I think that this the only null pointer here (4)
}
My thought is that dereferencing of the null pointer takes place only in the last case. Am I right? Is there difference between compile time null pointers and runtime according to C++ Standard?
Only the first and the last are null pointers. The others are results of reinterpret_cast
and thus operate on implementation defined pointer values. Whether the behavior is undefined for them depends on whether there is an object at the address you casted to.