firebush
firebush

Reputation: 5850

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?

Upvotes: 6

Views: 1066

Answers (1)

Anon Mail
Anon Mail

Reputation: 4770

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.

Upvotes: 9

Related Questions