Sanich
Sanich

Reputation: 1835

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!

Upvotes: 3

Views: 195

Answers (1)

EmDroid
EmDroid

Reputation: 6066

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).

Upvotes: 3

Related Questions