#include <memory>
class B;
class A {
public:
std::shared_ptr<B> ptr_to_b;
A() { std::cout << "A constructor" << std::endl; }
~A() { std::cout << "A destructor" << std::endl; }
};
class B {
public:
std::shared_ptr<A> ptr_to_a;
B() { std::cout << "B constructor" << std::endl; }
~B() { std::cout << "B destructor" << std::endl; }
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->ptr_to_b = b;
b->ptr_to_a = a;
// 这里a和b相互引用,引用计数都为2,离开作用域后无法正常销毁
return 0;
}
为啥离开作用域后无法正常销毁?
#include <memory>
class B;
class A {
public:
std::shared_ptr<B> ptr_to_b;
A() { std::cout << "A constructor" << std::endl; }
~A() { std::cout << "A destructor" << std::endl; }
};
class B {
public:
std::weak_ptr<A> ptr_to_a;
B() { std::cout << "B constructor" << std::endl; }
~B() { std::cout << "B destructor" << std::endl; }
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->ptr_to_b = b;
b->ptr_to_a = a;
// 现在不会出现循环引用问题,对象可以正常销毁
return 0;
}
这为啥就正常呢?