What is happening during `delete this;` statement?

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

    I would be very cautious about the context in which you free memory. Whilst calling "delete this;" will attempt to free the memory associated with the class structure, that operation has no means of deducing the context of the original memory allocation, ie, if it's allocated from the heap or the stack. My advise would be to rework your code so that the deallocation operation is invoked from an external context. Note that this is different from deallocating structures internal to the class, in that case, use the destructor.

提交回复
热议问题