After destroying object, the code in the function still runs

14 views Asked by At

I have this code which has a static shared_ptr<Object>. In its function member, I changed the shared_ptr to point to nullptr

#include<iostream>
#include<utility>
#include<memory>

using namespace std;

class Object;

static shared_ptr<Object> pObj;

class Object {
public:
    Object() {
        cout << "Object()" << endl;
        this->a = 20;
    }
    ~Object() {
        cout << "~Object()" << endl;
    }
    void run() {
        cout << "Object run" << endl;
        pObj = nullptr;
        cout << "Object why it's still running? a = " << this->a << endl;
    }
    int a;
};

int main() {
    pObj = make_shared<Object>();
    pObj->run();
    return 0;
}

The code returns a result

Object()
Object run
~Object()
Object why it's still running? a = 20

As I know, the object ends its life time when its destructor is called?. So I think that this->a after pObj = nullptr is an undefined behavior. But what if after setting pObj = nullptr, I only call cout << "Object why it's still running?" or another static function or static variable or a member function of a static Object, etc. Will it be valid?

In run(), if I use delete this, I will immediately get a crash dump, but in this case, it works (even if it might be an undefined behavior). Why is that?

I think if run is a static function, it will be valid because static function exists separately with the object. Am I right?

0

There are 0 answers