如何避免shared_ptr的内存泄漏? [英] How to avoid memory leak with shared_ptr?
问题描述
考虑以下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;
}
有是的没有输出的。的没有desctructor 的被调用。内存泄漏。
我始终认为,智能指针有助于避免内存泄漏。
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?
推荐答案
如果你有这样的循环引用,一个对象应持有<一个href=\"http://www.boost.org/doc/libs/1%5F41%5F0/libs/smart%5Fptr/weak%5Fptr.htm\"><$c$c>weak_ptr$c$c>其他,而不是一个的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
实例周期不会被回收。例如,如果的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."
的感谢,幽谷,您的链接。的
这篇关于如何避免shared_ptr的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!