What is happening during `delete this;` statement?

前端 未结 7 2813
余生分开走
余生分开走 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:25

    delete this; is allowed, it deletes the object.

    Both your code snippets have undefined behavior - in the first case deleting an object that has already been deleted, and in the second case deleting an object with automatic storage duration.

    Since behavior is undefined, the standard doesn't say whether they will cause an exception or heap corruption. For different implementations it could be either, neither, or both, and it may or may not be the same each time you run the code.

提交回复
热议问题