Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 513
firebush Avatar asked Dec 07 '15 16:12

firebush


People also ask

What is the difference between shared_ptr and Weak_ptr?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.

Should you use shared_ptr?

Use shared_ptr if you want to share ownership of a resource. Many shared_ptr can point to a single resource. shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed.

Is Weak_ptr lock thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe. You can't read/write to a single smart pointer across threads. Access to g_s like you did isn't safe, be it a shared_ptr or a weak_ptr.

What does Weak_ptr lock do?

weak_ptr::lockCreates a new std::shared_ptr that shares ownership of the managed object. If there is no managed object, i.e. *this is empty, then the returned shared_ptr also is empty.


1 Answers

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.

like image 156
Anon Mail Avatar answered Oct 13 '22 02:10

Anon Mail