Std :: weak_ptr: lock or shared_ptr constructor?

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

  • Use lock()
  • Pass weak_ptr the shared_ptr constructor

Both of them produce shared_ptr , and the lock returns nullptr if weak_ptr empty and the shared_ptr constructor throws an exception.

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

+5
source share
1 answer

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

You can use this function and the constructor std :: shared_ptr to acquire temporary ownership of the managed object referenced by std :: weak_ptr. The difference is that the std :: shared_ptr constructor throws an exception when its argument std :: weak_ptr is empty, while std :: weak_ptr :: lock () creates an empty stand :: shared_ptr.

It makes me believe that you are choosing which one to use based on whether you want to get an exception or not. A constructor can be used when it should work, while lock can be used when it is possible that it will not work, and you can check.

+7
source

Source: https://habr.com/ru/post/1237590/


All Articles