Why does the call method through a null pointer "work" in C ++?

Possible duplicate:
Calling a class method using a NULL class pointer

#include <iostream> using namespace std; class test { int i; public: test():i(0){ cout << "ctor called" << endl;} void show() { cout<<"show fun called"<<endl; } }; int main(int argc , char *argv[]) { test *ptr = NULL; ptr->show(); return 0; } 

clearly no ctor will be called. Is this a standard? or just optimizing the compiler since this pointer is not used in the show () member function?

+7
source share
4 answers

A pointer is not needed to call a method. The type of the pointer is known; therefore, the code for the method is known. The method does not use this , so it works fine with code. This behavior is undefined, but it’s more efficient not to check if the pointer is NULL, so it starts.

+22
source

If you look at the assembly (at least for one compiler), you can understand why it works (although this behavior is undefined, as many have pointed out). For these two lines:

 test *ptr = NULL; ptr->show(); 

This assembly is generated (in one compiler I just tried):

 00000004: C7 45 FC 00 00 00 mov dword ptr [ebp-4],0 00 0000000B: 8B 4D FC mov ecx,dword ptr [ebp-4] 0000000E: E8 00 00 00 00 call ?show@test @@QAEXXZ 

It pushes NULL (0) onto the stack and calls the method, since the address of the method does not depend on the actual instance of the object.

+8
source

Not valid, the behavior is undefined, and the actual results depend on your compiler.

+1
source

Well, firstly, it is not valid, as it causes undefined behavior. You really ask why the compiler allows this, and the answer is that this is bone code that just doesn't appear in a real application, so why bother? The real problem arises when the pointer becomes invalid at runtime in a way that cannot be predicted by static code analysis.

The compiler should not hold your hand; it should compile your code in accordance with the standard. If it offers useful warnings, then it’s great, but it’s not syntactically or semantically illegal, you just write code that causes undefined behavior.

-one
source

All Articles