Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to use weak_ptr.lock() just to test if it points to a valid object?

It seems kind of inefficient to have to create a temporary shared_ptr just to see if the weak_ptr is pointing to a valid object. I don't want to even access the object. This is because I have a function that returns a weak_ptr from a vector of shared_ptr and if it returns an empty weak_ptr then that means the object doesn't already exist with that GUID.

So I'm just testing if an object exists.

Is there another way to check to see if the weak_ptr is or isn't empty, without creating a shared_ptr?

like image 364
EddieV223 Avatar asked Nov 12 '12 21:11

EddieV223


People also ask

When should I use Weak_ptr?

By using a weak_ptr , you can create a shared_ptr that joins to an existing set of related instances, but only if the underlying memory resource is still valid. A weak_ptr itself does not participate in the reference counting, and therefore, it cannot prevent the reference count from going to zero.

What is Weak_ptr lock?

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.

What is Weak_ptr in C++?

(since C++11) std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.

Is Weak_ptr lock thread safe?

Note that the control block used by std::weak_ptr and std::shared_ptr is thread-safe: different non-atomic std::weak_ptr objects can be accessed using mutable operations, such as operator= or reset , simultaneously by multiple threads, even when these instances are copies or otherwise share the same control block ...


1 Answers

You can use the expired() member function.

like image 110
Armen Tsirunyan Avatar answered Oct 11 '22 04:10

Armen Tsirunyan