What is happening during `delete this;` statement?

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

    In both cases your heap will get corrupted. Of course, you can't use in option 2 "->" if the left value (in this case, "a") is not a pointer, the correct form in option 2 would be a.done(); But yeah, you should get a heap corruption if you try to delete 1) what's been already deleted, or 2) local variable.

    Calling "delete this" is technically valid and frees the memory.

    EDIT I was curious and actually tried this:

    class foo 
    {
    public: 
        foo(){} 
        ~foo(){} 
        void done() { delete this; } 
        void test() { x = 2; }
        int getx() { return x; }
    private: 
        int x; 
    } ;
    
    
    int main(int argc, char* argv[])
    {
        foo *a = new foo();
        a->done();
        a->test();
        int x = a->getx();
        printf("%i\n", x);
        return x;
    }
    

    A call to printf will succeed, and x will hold the value 2.

提交回复
热议问题