Accessing Static Members Using Null Pointers in C
In C , it is generally understood that accessing members of a class or struct through an uninitialized pointer is undefined behavior. However, static members seem to exhibit a peculiar exception. The following code snippet showcases this behavior:
<code class="cpp">#include <iostream> class demo { public: static void fun() { std::cout << "fun() is called\n"; } static int a; }; int demo::a = 9; int main() { demo *d = nullptr; d->fun(); std::cout << d->a; return 0; }</code>
When this code is compiled and run, it produces the expected output ("fun() is called" and "9") without any errors. This raises the question: is there any harm in this approach?
Understanding the Behavior
To understand this behavior, it's important to delve into the definition of accessing static members in C . According to the language standard, the dot operator (.) used to access static members is essentially equivalent to dereferencing a null pointer followed by accessing a member of the object it would point to. In this case, the null pointer refers to the static member of the class, not an instance of it.
This explains why static member access using null pointers is not inherently undefined behavior. The critical aspect is that the accessing expression, such as *d or d->a, is evaluated without any lvalue-to-rvalue conversions or other operations that would typically trigger undefined behavior when dealing with uninitialized pointers.
Indirection Through Null Pointers
The question then arises: does indirection through null pointers always result in undefined behavior? The answer is surprisingly nuanced. There is an open CWG issue (#232) that addresses this very topic, and the consensus seems to be that indirection through a null pointer alone does not constitute undefined behavior.
However, it's important to note that in certain contexts, such as when the lvalue is converted to an rvalue or a non-static member function is invoked with a null pointer, undefined behavior may arise.
Conclusion
In conclusion, while accessing static members using null pointers is not inherently undefined behavior in C , it should be used cautiously. It's crucial to understand the subtleties of lvalue-to-rvalue conversions and other operations that can trigger undefined behavior when dealing with pointers.
The above is the detailed content of Is Accessing Static Members Using Null Pointers in C Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!