Possible Duplicates:
Is it OK to use "delete this" to delete the current object?
Should objects delete themselves in C++?
I just came across this question on programmers.stackexchange and saw the question about doing a delete this;
inside a member function.
From what I understand it is generally a no-no however there are some circumstances where this could be useful. When would something like that be useful and what are the technical reasons for not doing it?
Generally speaking, it's a bad idea as you're technically inside a member function when you do it and suddenly every member of that class is now invalid. Obviously if you do not touch anything after the delete this;
call, you'll be okay. But it's very easy to forget these things, try and access a member variable and get undefined behavior and spend time at the debugger.
That said, it's used in things like Microsoft's Component Object Model (COM), when releasing a component (NOTE, this isn't exactly what they do as CashCow points out and is for illustrative purposes only):
void AddRef() { m_nRefs++; }
void Release()
{
m_nRefs--;
if(m_nRefs == 0)
delete this;
// class member-variables now deallocated, accessing them is undefined behaviour!
} // eo Release
That said, in C++ we have smart pointers (such as boost::shared_ptr
) to manage the lifetimes of objects for us. Given that COM is inter-process and accessible from languages such as VB, smart pointers were not an option for the design team.
delete this;
is commonly used in reference counting patterns. The object deletes itself when its reference count drops to zero. It is perfectly ok provided no further reference is made to the object being deleted. It also requires that the said object resides on the heap/free store.
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