How does this code work in C ++? Uninitialized pointer

Possible duplicate:
What happens when I call a member function on a NULL object pointer?

class A { public: void foo() { cout << "Work";} void bar() { this->foo(); }//new edit, works too! }; class B { private: A *a; //never initialized public: A& getA() { return *a; } }; void SomeFunction() { B *b = new B(); B& bRef = *b; bRef.getA().bar();//edited delete b; } 

I called SomeFunction () without initializing "a", and it still prints "Work" correctly. I do not understand why this should have happened with a segmentation error!

+4
source share
3 answers

Remember that classes are just a C ++ construct. When compiling, all methods of the class are only static methods that take the hidden this parameter.

Given that your foo() method never refers to any data members, it never needs to use it, so it works fine, despite the uninitialized value of this.

+5
source

This behavior is undefined, but it will work on most compilers, since foo not virtual and does not use the this pointer.

+10
source

Semantically

 of(args) 

coincides with

 f(o, args) 

So you can consider the function you are calling ( A::foo() ) so that it is equivalent:

 void A_foo(A* pthis) { cout << "Work"; } 

As you can see, pthis never dereferenced, so there is no invalid memory access. Even if you type this->foo() , this is exactly the same call, and this does not need to be dereferenced.

At least this is one of the common ways to implement a compiler. This is undefined as to what might happen, so running the code on Death Station 9000 can lead the kitten into space instead. Think about kittens!

+3
source

Source: https://habr.com/ru/post/1440473/


All Articles