[英]How to avoid memory leak with shared_ptr?
Consider the following code. 请考虑以下代码。
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.
没有调用desctructor 。 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? 如果我需要在类中进行交叉引用,我该怎么办?
If you have circular references like this, one object should hold a weak_ptr
to the other, not a shared_ptr
. 如果你有像这样的循环引用,一个对象应该将
weak_ptr
保存到另一个,而不是shared_ptr
。
From the shared_ptr
introduction : 来自
shared_ptr
介绍 :
Because the implementation uses reference counting, cycles of
shared_ptr
instances will not be reclaimed.由于实现使用引用计数,因此不会回收
shared_ptr
实例的循环。 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."例如,如果
main()
将shared_ptr
保存到A
,它直接或间接地将shared_ptr
保存回A
,则A
的使用计数将为2.原始shared_ptr
破坏将使A
悬空使用计数为1。weak_ptr
“打破周期”。
Thanks, Glen, for the link. 谢谢,格伦,链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.