How to avoid memory leak with shared_ptr?(如何使用 shared_ptr 避免内存泄漏?)
问题描述
考虑以下代码.
using boost::shared_ptr;
struct B;
struct A{
~A() { std::cout << "~A" << std::endl; }
shared_ptr<B> b;
};
struct B {
~B() { std::cout << "~B" << std::endl; }
shared_ptr<A> a;
};
int main() {
shared_ptr<A> a (new A);
shared_ptr<B> b (new B);
a->b = b;
b->a = a;
return 0;
}
没有输出.没有析构函数被调用.内存泄漏.我一直相信智能指针有助于避免内存泄漏.
There is no output. No desctructor is called. Memory leak. I have always believed that the smart pointer helps avoid memory leaks.
如果我需要在类中交叉引用怎么办?
What should I do if I need cross-references in the classes?
推荐答案
如果你有这样的循环引用,一个对象应该持有一个 weak_ptr 到另一个,而不是 shared_ptr.
If you have circular references like this, one object should hold a weak_ptr to the other, not a shared_ptr.
来自shared_ptr 介绍:
因为实现使用了引用计数,shared_ptr 实例的周期不会被回收.例如,如果 main() 持有一个 shared_ptr 到 A,它直接或间接地持有一个 shared_ptr 回到A,A 的使用次数将是 2. 原始 shared_ptr 的破坏将使 A 与使用计数为 1.使用 weak_ptr 来中断循环".
Because the implementation uses reference counting, cycles of
shared_ptrinstances will not be reclaimed. For example, ifmain()holds ashared_ptrtoA, which directly or indirectly holds ashared_ptrback toA,A's use count will be 2. Destruction of the originalshared_ptrwill leaveAdangling with a use count of 1. Useweak_ptrto "break cycles."
感谢 Glen 提供链接.
这篇关于如何使用 shared_ptr 避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 shared_ptr 避免内存泄漏?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
