混淆:"delete(this);";问题. [英] confused: "delete(this);" problem.

查看:78
本文介绍了混淆:"delete(this);";问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Str
{
public:   
    void f()
    {
        delete this;
    }

    ~Str()
    {
        cout<<"Inside destructor..."<<endl;
        delete this;
    }
};


我正在独自学习C ++,并尝试了一些尝试.

为什么要删除此"?在析构函数中导致程序进入无限循环?如果在注释析构函数的删除此内容"后在函数f()中执行此操作,它的效果很好.陈述?
我正在为该类创建对象,如下所示:
Str obj =新的Str;
我正在使用用于C ++的VS编译器.
在类析构函数中删除此"有什么问题?

[enhzflep编辑]:问题标题,感到困惑:删除此问题--->困惑:删除(this);"问题


I am learning C++ on my own and trying few things.

Why having "delete this;" in destructor causes the program to go to an infinite loop? While it does fine if i do it in a function f() after commenting destructor`s "delete this;" statement?
I am creating object for the class as follows:
Str obj = new Str;
I am using VS compiler for c++.
What is the problem having "delete this" in class destructor??

[enhzflep edit]: Question title, confused: delete this problem ---> confused: "delete(this);" problem

推荐答案

它正在无限循环中进行,因为delete将调用detractor,然后它将用于其自己的内存释放过程.因此,当您在析构函数中执行此操作时,它会继续调用自身.

要了解有关删除的更多信息: http://www.cplusplus.com/reference/std/new/operator %20delete/ [ ^ ]
It is going in infinite loop because delete will call detractor and than it go for its own memory release procedure. so when u do this in destroctor it keep calling itself.

To Know more about Delete : http://www.cplusplus.com/reference/std/new/operator%20delete/[^]


因为delete this;调用了对象的析构函数.
Because delete this; calls object''s destructor.


class Str
{
public:
    void f()
    {
        //Removed: delete this;
    }

    ~Str()
    {
        cout<<"Inside destructor..."<<endl;
        //Removed: delete this;
    }
};



这是您的课程,您必须创建类似
的对象



this is your class n u must be creating objects like

Str s = new Str;



唯一的办法就是释放内存,



the only was to free this memory is by doing

delete s;   //Do this from outside where u did new



从课堂之外.因为delete s将调用析构函数并释放分配给S的内存.请勿在类内部的任何地方执行delete this.



from outside the class. as delete s will call the destructor and release memory allocated to S. don''t do delete this anywhere inside class.


这篇关于混淆:"delete(this);";问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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