Why I can access member functions even after the object was deleted?

So, my question is, why I’m still able to call Go_XXX_Your_Self() and Identify_Your_Self() even after the object was deleted?

Because of undefined behavior.

Is this how it works in C++? (is there even after you delete it?)

Because of undefined behavior. There is no guarantee that it will work the same on other implementations. Again, undefined behavior.

Also can you check to see if it’s not there? (I know theoretically is not possible but I’m curious to see what methods are out there)

delete MC1;
MC1 = nullptr;

By setting the pointer to nullptr after deleteing it, the runtime is most likely to detect that you are accessing an invalid, you-have-no-right-to-use location. Also, by diligently doing this for all applicable pointers, you have the ability to check if the object is valid or not (valid if non-nullptr).

if(my_ptr) {
   // my_ptr is most possibly valid (though you can still go wrong)
   // use my_ptr
}

Similarly, you should also set raw pointers to nullptr when they aren’t yet initialized to some valid address.

MyClass* some_ptr = nullptr;
...

But again, if you have access to modern C++11 facilities, it’s much better not to use raw pointers at all, and just use std::unique_ptr or std::shared_ptr (depending on your required semantics). And on future C++ standard revisions, you may also want to use the proposed std::exempt_ptr which is a non-owning, observe-only pointer wrapper.

Leave a Comment