seung hwan Son
seung hwan Son

Reputation: 305

Why shared_ptr and weak_ptr working like this? (for resolve circular ref)

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

Answers (1)

Mohamad Elghawi
Mohamad Elghawi

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 a - a use_count = 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

  • Destruct a which prints 1 as b's use_count

Upvotes: 4

Related Questions