will weak_pointer.lock() increment the ref count of original shared_ptr which was used to create weak_ptr

StackOverflow https://stackoverflow.com/questions/22212255

  •  10-06-2023
  •  | 
  •  

Question

As per my understanding, weak pointer is used to cyclic dependency problem occurs if we use all shared_ptr objects and if there is a cyclic dependency. Weak pointers are used to break the cycles. weak pointers achieves this by using lock() which will create shared pointer.

class A { shared_ptr<B> b; ... };
class B { weak_ptr<A>   a; ... };
shared_ptr<A> x(new A); // +1
x->b = new B;           // +1
x->b->a = x;            // No +1 here

But now assume that I created lock calling x->b->a.lock(), so ref count of x will become 2. and if x leaves the scope, still there will be memory leak right? Because I created a shared pointer using lock() and ref count became 2. Please let me know whether my understanding is correct or not.

Was it helpful?

Solution

There are two distinct reference counts involved for a shared_ptr shared object:

  • The number of references to the object, i.e. shared_ptr instances.
  • The number of references to the control block, i.e. shared_ptr and weak_ptr instances.

A weak_ptr contributes only to the latter count. When all shared_ptr instances have been destroyed, the object deleter is called, which usually is the default one that destroys the object. The control block still exists if there are weak pointers. When also all weak pointers have been destroyed, the control block is destroyed.

So (ignoring possible optimization of caching object pointer directly in each shared_ptr instance), in your case you have x pointing (hidden for you) to the control block, which has a pointer to the A instance. And you have the b member of that instance pointing to a second control block, which has a pointer to a B instance. Finally that instance has a pointer to the control block that x points to, which is circular yes, but not a circularity of ownership.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top