zeno zeno - 1 year ago 88
C++ Question

What is diffrence between lock() and expired()? weak_ptr C++

recently i started at c++ 11.
I study about weak_ptr. there exist two way getting raw pointer.

  1. lock() function

    shared_ptr<Foo> spFoo = wpPtr.lock();

    if(spFoo) {

  2. expired() function

    shared_ptr<Foo> spFoo = wpPtr.lock();

Which is better way?

what is difference between first and second.

Answer Source

So shared ptr and weak ptr are thread safe, in that if you have an instance of the object local to a given thread, and they share a common pointed-to object, you can interact with them in one thread and another and everything works.

For this to work properly, you have to use them properly.

wp.expired() is only useful to do things like "remove every expired weak ptr from a buffer". It is not useful for the purpose you put it.

Every weak pointer, once expired, remains expired. But an engaged weak pointer can become expired immeidately after you verify it is engaged.

if(!wpPtr.expired())  {
  // <<--- here
  shared_ptr<Foo> spFoo = wpPtr.lock();

At <<--- here we know nothing about the state of wpPtr in a multi-threaded environment. It could be expired or not expired. On the other hand:

if(wpPtr.expired())  {
  // <<--- there

At <<--- there we do know the weak pointer is expired.

Like with file io and other kinds of "transactional" operations, the only way to check if you can do something is try to do it. Between determining you should be able to do it and doing it, the state could change and the operation could fail.

You can sometimes work out that you almost certainly could not do it early, which is sometimes useful, but you cannot be certain you can do it until you try. The attempt to try can fail, at which point you handle the error.

if(auto spFoo = wpPtr.lock())  {

this is the "right" way to interact with a weak pointer. Test for the validity of the weak pointer and get the shared pointer in the same operation.

Creating a spFoo outside of the if() header is acceptable, I prefer this technique as the scope of the spFoo is limited exactly to the zone where it is valid.

The other preferred technique is early exit, where you have written your code to be SFINAE friendly:

auto spFoo = wpPtr.lock();

if(!spFoo) return error("wp empty");


which makes the "expected" execution of the code flow in a flat line without indentation or conditions or jumps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download