Consider the following program:
<code class="cpp">#include <iostream> class Demo { public: static void func() { std::cout << "func() called" << std::endl; } static int num = 9; }; int main() { Demo* d = nullptr; d->func(); std::cout << d->num << std::endl; return 0; }
This program compiles and runs without errors, while accessing static members through a null pointer is generally considered undefined behavior. Why is this allowed?
TL;DR:
The given program does not trigger undefined behavior because indirection through a null pointer is not inherently problematic unless it involves further operations that rely on a valid object identity.
Explanation:
Whether indirection through null pointers is intrinsically undefined behavior has been a matter of debate. The only questionable operation in the program is the evaluation of the expression d->a.
d->a is equivalent to (*d).a due to pointer dereferencing rules. However, even if *d is undefined, the expression *d is still evaluated, especially when its result is discarded, as in the case of d->a. This behavior is well-defined.
The behavior with static members is different from accessing non-static members through a null pointer, which should indeed trigger undefined behavior since it implies an invalid object identity. Accessing static members, in contrast, does not require object identity, and their behavior is explicitly defined in the standard.
The given program does not pose any harm because the evaluation of *d is allowed in the context of accessing static members. Indirection through null pointers alone does not necessarily cause undefined behavior, but it is important to be aware of potential risks associated with further operations that require object identity.
The above is the detailed content of Why is it allowed to access static members using a null pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!