delete this

Hi,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void TestDeleteThis::deleteThisObject() {
	cout << "into delete method1" << endl;
	delete this;
}
int main(){

	
	TestDeleteThis td1;
	td1.i1 = 10;
	td1.deleteThisObject();
	cout << td1.i1 << endl; // line 1

return 0;
}


I thought that the above program would crash as the local objects are not stored in the heap. I can actually see the output of the program as 10 at line 1 and it seems to have worked correctly. Can someone please explain?

Thanks in Advance
It's undefined behavior.

Sometimes undefined behavior will mean it crashes... other times it means it will make your program act very strangely... and other times it will mean it proceeds as if nothing out of the ordinary had happened. There's no way to know what's going to happen because it's undefined.
Ok, Thanks
Add this = NULL; after calling operator delete to make it always crash :)
Topic archived. No new replies allowed.