Reputation: 305
I want know about shared_ptr. After study, I know that the weak_ptr can resolve the circular reference problem in shared_ptr and, I write some code for testing it.
Code
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;
}
Output
a ref count: 1
b ref count: 1
a ref count: 1
b ref count: 2
A dtor: 1
B dtor: 0
I don't know why this code working like this. I think "A dtor: 2" and "B dtor: 0" will be corrent result. Please give me answer for it.
Upvotes: 1
Views: 94
Reputation: 2124
b
is destructed before a
(since destruction here occurs in the opposite order of construction) which reduces it's use_count
by 1.
Construct b - b use_count = 1
Assign b to A::b_ member - b use_count = 2
Assign a to B::a_ member - a use_count = 1
Destruct b - b use_count = 1
Upvotes: 4