简体   繁体   中英

std::weak_ptr: lock or shared_ptr constructor?

There seem to be two ways to temporarily grab ownership of the resource pointed to by a weak_ptr :

  1. Use lock()
  2. Pass the weak_ptr to a shared_ptr constructor

Both of these produce a shared_ptr , with the lock returning a nullptr in the case that the weak_ptr is empty and the shared_ptr constructor throwing an exception.

So the question is: when should one or the other be used? Are there general guidelines or best practices related to this?

Copied from http://en.cppreference.com/w/cpp/memory/weak_ptr/lock

Both this function and the constructor of std::shared_ptr may be used to acquire temporary ownership of the managed object referred to by a std::weak_ptr. The difference is that the constructor of std::shared_ptr throws an exception when its std::weak_ptr argument is empty, while std::weak_ptr::lock() constructs an empty std::shared_ptr.

That leads me to believe that you pick which one to use based on whether you want an exception thrown or not. The constructor can be used when it must work, whereas lock can be used when it's possible that it won't work and you can check.

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