What is the use of quot;delete thisquot;?(“删除这个有什么用?)
问题描述
今天,我看到了一些遗留代码.在析构函数中有一个类似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.
这篇关于“删除这个"有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“删除这个"有什么用?
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07