Accessing Class Members on a NULL Pointer
Despite being declared as a pointer to an instance of type Foo, the foo variable is initialized to 0, making it a null pointer. This may seem counterintuitive, as accessing members of a null pointer is typically undefined behavior. However, certain circumstances allow this behavior.
Non-Virtual Method Invocation
The non-virtual method say_hi() is successfully invoked despite the null pointer because it is not a virtual method. Virtual methods require a valid object to determine which function to call based on the object's type. Non-virtual methods, on the other hand, have a predetermined function address that the compiler uses to generate a direct function call instruction.
Specifically, the compiler generates code equivalent to the following:
void Foo_say_hi(Foo* this); Foo_say_hi(foo);
Since the say_hi() function does not reference the this pointer, it bypasses the need to dereference a potentially null pointer.
Object Allocation
The foo variable is a local variable within the main function, so it is allocated on the function's stack. As a pointer variable, the actual object it points to is not allocated here. The null value indicates that the pointer does not reference a valid object.
The above is the detailed content of Why Does Calling a Non-Virtual Method on a NULL Pointer Not Result in Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!