简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM