【C++基础】 delete this详解

 

在类的成员函数中能不能调用delete this?答案:可以

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    void f() {
        cout<<"delete this"<<endl;
        delete this;
    };
};

int main()
{
    {
      A a;
    }
}

 

问4:如果在类的析构函数中调用delete this,会发生什么?

答:实验告诉我们,会导致堆栈溢出。

delete的本质是将调用一个或多个析构函数,然后,释放内存。显然,delete this会去调用本对象的析构函数,而析构函数中又调用delete this,形成无限递归,造成堆栈溢出,系统崩溃。

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    ~ A() {
        cout<<"delete this"<<endl;
        delete this;
    };
};
int main()
{
    {
      A a;
    }
}

参考资料

 

1. c++ delete this

 

posted @ 2021-08-03 11:17  苏格拉底的落泪  阅读(399)  评论(0编辑  收藏  举报