我想知道shared_ptr。经过研究,我知道weak_ptr可以解决shared_ptr中的循环引用问题,并且编写一些代码对其进行测试。
代码
class B;
class A
{
public:
std::shared_ptr<B> _b;
~A()
{
std::cout << "A dtor: " << _b.use_count() << std::endl;
}
};
class B
{
public:
std::weak_ptr<A> _a;
~B() { std::cout << "B dtor: " << _a.use_count() << std::endl; }
};
int main()
{
{
std::shared_ptr<A> a(new A);
std::shared_ptr<B> b(new B);
std::cout << "a ref count: " << a.use_count() << std::endl;
std::cout << "b ref count: " << b.use_count() << std::endl;
a->_b = b;
b->_a = a;
std::cout << "a ref count: " << a.use_count() << std::endl;
std::cout << "b ref count: " << b.use_count() << std::endl;
}
std::cin.get();
return 0;
}
输出
a ref count: 1
b ref count: 1
a ref count: 1
b ref count: 2
A dtor: 1
B dtor: 0
我不知道为什么这段代码会这样工作。我认为“A dtor:2”和“B dtor:0”将是正确的结果。请给我答案。
最佳答案
b
在a
之前被破坏(因为此处的破坏以相反的顺序发生),从而将其use_count
减少1。
关于c++ - 为什么shared_ptr和weak_ptr像这样工作? (用于解决循环引用),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33894162/