Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening during `delete this;` statement?

Tags:

c++

memory

Please consider the following code:

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

What is happening (and is it valid?) in the following two options:

option 1:

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

option 2:

void main()
{
   foo a;
   a.done();
}

Will the second delete a; statement at option 1 will cause an exception or heap corruption?

Will option2 cause an exception or heap corruption?

like image 851
NirMH Avatar asked Jan 11 '12 13:01

NirMH


1 Answers

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.

like image 51
Steve Jessop Avatar answered Oct 10 '22 09:10

Steve Jessop