智能指针不够智能
Smart Pointer isn't smart enough
下面是一个例子:
template<typename T>
struct smart { //Smart Pointer class
smart();
~smart();
smart(const smart& copy);
T* target;
int count;
};
struct atest {
smart<atest> next;
};
void Garbage() {
smart_ptr<atest> Test=smart<atest>(new atest);
//Test.count == 1
Test->next=Test;
//Test.count == 2
//Test.target == Test->next.target
}
//Test.count == 1
//Test'll never be deleted! because it contains itself.
int main() {
for (int i=0;i<10000000;i++) {
Garbage();
}
}
有没有办法让Test
在Garbage
方法结束后删除自己?还有一个问题,智能指针还有其他漏洞吗?
你的问题很模糊,但我认为这是关于循环引用的,你应该使用"弱"智能指针来避免这种情况。您可以在这里阅读更多关于如何使用weak_ptr打破循环的信息。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 为什么程序员同时使用 std::bad_alloc 和 std::exception.是否 std::例外 仅是不够的
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 构造智能点数据类型以及普通数据类型的通用方法
- 编译器不会使用 -std=c++11 编译智能指针
- 为什么C++不支持对未初始化变量进行智能分析?
- 具有智能指针的多态性
- 智能指针不够智能