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

EddieV223 picture EddieV223 · Nov 12, 2012 · Viewed 8.5k times · Source

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?

Answer

Armen Tsirunyan picture Armen Tsirunyan · Nov 12, 2012

You can use the expired() member function.