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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With