“删除这个"有什么用? [英] What is the use of "delete this"?

查看:44
本文介绍了“删除这个"有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我看到了一些遗留代码.在析构函数中有一个类似delete this"的语句.我认为,这个调用将是递归的.为什么它有效?

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?

我在Y!上进行了一些快速搜索,发现如果需要限制用户创建堆栈对象,我们可以将析构函数设为私有并提供删除实例的接口.在提供的接口中,我们必须在这个指针上调用delete.

I made some quick search on Y!, I found that if there is a need to restrict the user to create the stack object, we can make destructor private and provide an interface to delete the instance. In the interface provided, we have to call delete on this pointer.

还有其他情况可以使用这样的语句吗?

Are there any other situations for using such statements?

推荐答案

删除这个"通常用于引用计数的对象.对于引用计数的对象,何时删除的决定通常放在对象本身上.下面是一个 Release 方法的示例 [1].

"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 对象是这种模式的主要例子.

ATL COM objects are a prime example of this pattern.

[1] 是的,我意识到这不是线程安全的.

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

这篇关于“删除这个"有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆