8

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

3 Answers3

5

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.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • I believe it actually uses InterlockedDecrement i.e. atomic decrement otherwise it would not be thread-safe. In addition AddRef and Release are const functions with m_nRefs mutable or you could not copy objects and increase their reference count properly. – CashCow Dec 15 '10 at 12:31
  • @CashCow, you're right, but I was merely showing it as an example as opposed to showing the *exact* code that COM uses, however I've amended my answer to show that it's hypothetical. – Moo-Juice Dec 15 '10 at 12:33
5

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.

doron
  • 27,972
  • 12
  • 65
  • 103
0

I use it in my message handling. It is pre shared_ptr and it lets the message decide whether to delete itself (asynchronous) or unblock the sender (synchronous).

stefaanv
  • 14,072
  • 2
  • 31
  • 53