What is the use of “delete this”?

后端 未结 4 1002
北恋
北恋 2020-12-05 06:54

Today, I have seen some legacy code. In the destructor there is a statement like \"delete this\". I think, this call will be recursive. Why it is working?

4条回答
  •  粉色の甜心
    2020-12-05 07:27

    "delete this" is commonly used for ref counted objects. For a ref counted object the decision of when to delete is usually placed on the object itself. Here is an example of what a Release method would look like [1].

    int MyRefCountedObject::Release() {
      _refCount--;
      if ( 0 == _refCount ) {
        delete this;
        return 0;
      }
      return _refCount;
    }
    

    ATL COM objects are a prime example of this pattern.

    [1] Yes I realize this is not thread safe.

提交回复
热议问题