删除析构函数中的(this)指针 [英] delete (this) pointer in destructor

查看:74
本文介绍了删除析构函数中的(this)指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写该程序只是为了检查如果在类的析构函数中删除此指针会发生什么情况.这是我的代码

I wrote the program just to check what happens if we delete this pointer in the destructor of the classs. Here is my code

 class xxx{
    public: xxx(){cout<<"constructor called"<<endl;}
            ~xxx(){cout<<"destructor called"<<endl;delete(this);}  //deleting the 'this' pointer
 };
 int main(int argc, char *argv[])
 {
    xxx *x1=new xxx();
    delete x1;
    return 0;
 }

当我运行此程序时,它会导致无限循环打印被称为dectructor的".

When I run this program it results in indefinite loop printing "desctructor called".

delete 运算符和析构函数之间的关系是什么?当您在析构函数中使用删除此时,还会发生什么?

What is the relation between delete operator and destructor function? Also what happens when you use delete this in the destructor?

推荐答案

this->〜destructor 被调用,然后 delete(this)将再次调用<因此,code> this->〜destructor 会无限期地调用函数.

this->~destructor is called, then delete(this) will will again call this->~destructor thus results in calling function indefinitely.

这篇关于删除析构函数中的(this)指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆