Many may find it counterintuitive that accessing static class members using null pointers doesn't lead to runtime errors. This article dives into the technical details to explain this behavior and discusses potential pitfalls.
At the core of the discussion is the evaluation of null pointer dereference. While accessing class members through uninitialized pointers is generally undefined, static members are an exception. When accessing static members, the object expression (e.g., d->a) is essentially equivalent to (*d).a.
In this case, the argument to the static member function fun is d, which is evaluated but discarded. This is because the operation *d is a discarded value expression, meaning it's evaluated solely for its side effects (in this case, none).
The crux of the issue revolves around whether indirection through a null pointer inherently results in undefined behavior. The C standard provides somewhat conflicting guidance on this matter. However, a widely held interpretation is that mere indirection through a null pointer, without any further lvalue-to-rvalue conversion or other operations, does not invoke undefined behavior.
In the context of CWG-issue #232, the concept of "empty lvalues" was proposed to address the issue of null pointer dereference. However, it was never adopted.
The rationale for allowing the example code to execute without errors is that calling a static member function with a null pointer does not require the identity or stored value of the object. The value of the static member is simply accessed, without any further lvalue operations.
While accessing static members using null pointers is generally allowed, it's important to avoid using the . operator to access non-static members. Non-static member access requires the object to be valid, which could lead to undefined behavior when using null pointers.
The above is the detailed content of Why Does Accessing Static Class Members with Null Pointers Work?. For more information, please follow other related articles on the PHP Chinese website!