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.