Reputation: 391
Recently I started at C++11.
I studied about weak_ptr
. There exist two ways of getting raw pointer.
lock()
function
shared_ptr<Foo> spFoo = wpPtr.lock();
if(spFoo) {
spFoo->DoSomething();
}
expired()
function
if(!wpPtr.expired())
{
shared_ptr<Foo> spFoo = wpPtr.lock();
spFoo->DoSomething();
}
Which is the better way? What is different between the two ways?
Upvotes: 36
Views: 21979
Reputation: 275878
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 immediately after you verify it is engaged.
if(!wpPtr.expired()) {
// <<--- here
shared_ptr<Foo> spFoo = wpPtr.lock();
spFoo->DoSomething();
}
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()) {
spFoo->DoSomething();
}
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:
auto spFoo = wpPtr.lock();
if(!spFoo) return error("wp empty");
spFoo->DoSomething();
which makes the "expected" execution of the code flow in a flat line without indentation or conditions or jumps.
Upvotes: 45
Reputation: 14926
Below are the relevant operations for a weak_ptr
. You should go with option 1 because approach 2 is not thread-safe.
w.use_count()
The number ofshared_ptr
s that share ownership withw
w.expired()
returnstrue
ifw.use_count()
is zero,false
otherwise
w.lock()
Ifexpired
istrue
, returns a nullshared_ptr
; otherwise returns ashared_ptr
to the object to whichw
points.
(2) Not thread-safe
// let p be the last shared_ptr pointing at the same object as wpPtr
if (!wpPtr.expired())
{
// we enter the if-statement because wpPtr.use_count() is 1
// p goes out of scope on its thread, the object gets deleted
shared_ptr<Foo> spFoo = wpPtr.lock(); // null shared_ptr
spFoo->DoSomething(); // ERROR! deferencing null pointer
}
(1) Thread-safe
// let p be the last shared_ptr pointing at the same object as wpPtr
shared_ptr<Foo> spFoo = wpPtr.lock();
// now, wpPtr.use_count() is 2, because spFoo and p are both pointing at the object
// p goes out of scope on its thread, but spFoo is still pointing at the object
if(spFoo) {
spFoo->DoSomething(); // OK! safe to dereference
}
Upvotes: 9
Reputation: 18864
The second variant has two problems:
wpPtr.expired()
if (spFoo)
before dereferencing spFoo
The first variant is transactional, and is the one to use when you ultimately need to work with the object referred to by the weak pointer.
Upvotes: 7
Reputation: 15334
Option 1.
If you go with option 2 then between calling wpPtr.expired()
and calling wpPtr.lock()
the weak_ptr
could have expired and the line spFoo->DoSomething()
will try to dereference a null shared_ptr
.
Upvotes: 2
Reputation: 28932
To quote from cppreference.com:
std::weak::lock
effectively returns
expired() ? shared_ptr<T>() : shared_ptr<T>(*this)
use expired to check whether the underlying object is valid and lock to potentially promote the object to a std::shared_ptr
Upvotes: -1