开发者

Usefulness of 'delete this' in member function [duplicate]

This question already has answers here: Closed 12 years ago.

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 a开发者_StackOverflow中文版re 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜