Ale*_*tov 23 c++ boost memory-leaks smart-pointers 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;
}
Run Code Online (Sandbox Code Playgroud)
有没有输出.没有调用desctructor.内存泄漏.我一直认为智能指针有助于避免内存泄漏.
如果我需要在类中进行交叉引用,我该怎么办?
Jam*_*lis 52
如果你有像这样的循环引用,一个对象应该保持另一个对象weak_ptr,而不是a shared_ptr.
由于实现使用引用计数,
shared_ptr因此不会回收实例的循环.例如,如果main()保持shared_ptr对A,其直接或间接地保持shared_ptr回A,A的使用计数是2的原始的破坏shared_ptr会留下A与1.使用的使用计数悬空weak_ptr'打破循环’.
谢谢,格伦,链接.