什么是“删除此”的使用? [英] What is the use of "delete this"?

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

问题描述

今天,我看到了一些旧代码。在析构函数中有一个语句,如 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上做了一些快速搜索,我发现如果有需要限制用户创建堆栈对象,我们可以destructor private并提供一个接口来删除实例。在提供的界面中,我们必须对此指针调用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?

推荐答案

delete this通常用于ref计数对象。对于ref计数对象,何时删除的决定通常放在对象本身上。这里是一个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天全站免登陆