use of "delete"

consider this code:

class sample{
int i;
public:
void fun()
{
delete this;
}
};

void main()
{
sample *s=new sample;
s->fun(); // Statement 1
sample s1;
s1->fun(); // Statement 2
}

This program works fine[no compile or run time error]

But delete is only used to free memory allocated by "new"....and in statement 2
it is used to delete this pointer for an object created on stack....

so,there should be error on statement 2 but the program work fine.
Pls expalin.....
Really works? With what compiler? Consider:
sample s1; s1->fun();


+ After rewriting to s1.fun() it doesn't even take valgrind memory checker to crash with double free. Anyway, it's interesting, when is that useful to call "delete this"?
Last edited on
I am using gcc compiler
Freeing stack-allocated memory results in undefined behavior.
The standard does mandate that it cause a runtime error.
The program will never work as mentioned. Since s1 object is in stack you have to call the method using dot operator.

Anyway, deleting the "this" object from a method means, that object has no life after the method invocation and it will work fine for all the objects those are in heap. But it will crash the program if invoked using an object in stack as delete will work only for heap objects.

So its not a good practice to delete the object from a method as we don't know where the user of a class is going to create the object, in heap or stack.
Topic archived. No new replies allowed.