Accessing static member through invalid pointer: guaranteed to “work”? [duplicate]

it’s not clear whether “evaluation” here involves an actual dereference.

I read “evaluation” here as “the subexpression is evaluated.” That would mean that the unary * is evaluated and you perform indirection via a null pointer, yielding undefined behavior.

This issue (accessing a static member via a null pointer) is discussed in another question, When does invoking a member function on a null instance result in undefined behavior? While it discusses member functions specifically, I don’t see any reason that data members are any different in this respect. There is some good discussion of the issue there.

There was a defect reported against the C++ Standard that asks “Is call of static member function through null pointer undefined?” (see CWG Defect 315) This defect is closed and its resolution states that it is valid to call a static member function via a null pointer:

p->f() is rewritten as (*p).f() according to 5.2.5 [expr.ref]. *p is not an error when p is null unless the lvalue is converted to an rvalue

However, this resolution is in fact wrong.

It presupposes the concept of an “empty lvalue,” which is part of the proposed resolution for another defect, CWG defect 232, which asks the more general question, “Is indirection through a null pointer undefined behavior?”

The resolution to that defect would make certain forms of indirection through a null pointer (like calling a static member function) valid. However, that defect is still open and its resolution has not been adopted into the C++ Standard. Until that defect is closed and its resolution is incorporated into the C++ Standard, indirection via a null pointer (or dereferencing a null pointer, if one prefers that term) always yields undefined behavior.

Leave a Comment