Hi guys
Can someone please explain what will happen if I say:
Thank you....Code:delete this;
Printable View
Hi guys
Can someone please explain what will happen if I say:
Thank you....Code:delete this;
It depends entirely on the context in which you call it, and can range from exactly what you want it to do all the way to a disastrous crash.
Graham is correct. And actually, if you call this in a non-member function you will get a compiler error as well. :rolleyes:
Anyways...
If the object was allocated on the heap... It will call it's destructor, then free it. (And that's assuming the delete call matches the new call)
If it's an object on the stack, it will call the destructor.... And depending on the allocator used for new/delete calls when you call delete, this could crash, it might not. If this is a POD (plain old data) object, it probably will have no apparent effect if it does not crash on the delete call.
... or you end up in an endless recursion leading to a stack overflow if you do this in the destructor itself.
Please note that accessing any member after calling delete this result in undefined behaviour.
The statement delete this is used in COM when an object's reference count reaches zero.
delete this; makes sense only when the object creation is being managed by the class itself. That is, the class creates objects of itself using new then returns to the caller and then exposes an interface that does the delete.
Sorry, what does that mean?Quote:
Originally Posted by JamesSchumacher
Guys thank you very much !!!
I think I'm starting to get it.
Will some of you guys kindly enough, post a code examples for something that will work and the use of “delete this” is necessarily , and something that will crash the program. If it’s not too much hassle a brief explanation to the code will be great.
Once again THANK YOU!!!