What is happening during `delete this;` statement?

前端 未结 7 2836
余生分开走
余生分开走 2021-02-20 08:47

Please consider the following code:

class foo
{
public:
    foo(){}
    ~foo(){}
    void done() { delete this;}
private:
    int x;
};

What is

7条回答
  •  忘掉有多难
    2021-02-20 09:16

    Both would cause an error, what you want is:

    void main()
    {
       foo* a = new foo();
       a->done();
    }
    

    Which the compiler will expand to something like below, which I hope makes deleting "this" a bit less confusing.

    void __foo_done(foo* this)
    {
       delete this;
    }
    
    void main()
    {
       foo* a = new foo();
       __foo_done(a);
    }
    

    See also, Is it legal (and moral) for a member function to say delete this?

提交回复
热议问题