使用时,你有什么方法可以用脚射击自己boost::shared_ptr?换句话说,当我使用时,我必须避免哪些陷阱boost::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.内存泄漏.我一直认为智能指针有助于避免内存泄漏.
如果我需要在类中进行交叉引用,我该怎么办?