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. 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…