Please consider the following code:
class foo
{
public:
foo(){}
~foo(){}
void done() { delete this;}
private:
int x;
};
What is
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
.