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_ptr
instances will not be reclaimed. For example, ifmain()
holds ashared_ptr
toA
, which directly or indirectly holds ashared_ptr
back toA
,A
's use count will be 2. Destruction of the originalshared_ptr
will leaveA
dangling with a use count of 1. Useweak_ptr
to "break cycles."
感谢 Glen 提供链接.
这篇关于如何使用 shared_ptr 避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 shared_ptr 避免内存泄漏?


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01