Is there a way to distinguish between an assigned (possibly expired) weak_ptr and a non-assigned one.
weak_ptr<int> w1;
weak_ptr<int> w2 = ...;
I understand the following checks for either non-assignment or expiry, but is there a (cheaper?) check for only non-assignment?
if (!w.lock()) { /* either not assigned or expired */ }
Using std::weak_ptr::expired()
Output
You could try to create a shared pointer that accepts a weak pointer as a parameter and raises a std::bad_weak_ptr exception if a weak pointer is expired (or not assigned as in your case):
You can use two calls to
owner_before
to check equality with a default constructed (empty) weak pointer:This will only return
true
ifw{} "==" weak
, where"=="
compares owner, and according to en.cppreference.com:Since the default constructor constructs an empty weak pointer, this can only return
true
ifweak
is also empty. This will not returntrue
ifweak
has expired.Looking at the generated assembly (with optimization), this seems pretty optimized:
... compared to checking
weak.expired()
:... or returning
!weak.lock()
(~80 lines of assembly).