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 避免内存泄漏?
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
