Sanich Sanich - 1 year ago 47
C++ Question

Implementation of lock()

According to boost:


To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.


Again, from boost:

shared_ptr<T> lock() const;

//Returns: expired()? shared_ptr<T>(): shared_ptr<T>(*this).


As far as I understand, returning
shared_ptr<T>(*this)
means creating a new shared_ptr with reference count of 1; And this is definitely not what we want. So probably I'm not understand it right. Will someone explain? Thanks!

Answer Source

No, that is actually the point of shared_ptr - the copied instance will point to the same underlying data and increment the reference count for both instances.

That means that shared_ptr<T>(*this) will create an additional shared_ptr instance pointing to the same data and will increment the reference count for both this and the new instance.


It is actually more complicated in the real code, as the original shared_ptr data is accessed through the weak_ptr instance, but effectively the original shared_ptr data is shared at the end (with the shared reference count increased in all existing copies of the particular shared_ptr object).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download