|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Modifiers | ||||
| Observers | ||||
weak_ptr::lock | ||||
(C++26) | ||||
(C++26) | ||||
| Non-member functions | ||||
| Helper classes | ||||
(C++20) | ||||
| Deduction guides(C++17) |
std::shared_ptr<T> lock()constnoexcept; | (since C++11) | |
Creates a newstd::shared_ptr that shares ownership of the managed object. If there is no managed object, i.e.*this is empty, then the returnedshared_ptr also is empty.
Effectively returnsexpired()? shared_ptr<T>(): shared_ptr<T>(*this), executed atomically.
Contents |
Ashared_ptr which shares ownership of the owned object ifstd::weak_ptr::expired returnsfalse. Else returns default-constructedshared_ptr of typeT.
Both this function and the constructor ofstd::shared_ptr may be used to acquire temporary ownership of the managed object referred to by astd::weak_ptr. The difference is that the constructor ofstd::shared_ptr throws an exception when itsstd::weak_ptr argument is empty, whilestd::weak_ptr<T>::lock() constructs an emptystd::shared_ptr<T>.
#include <iostream>#include <memory> void observe(std::weak_ptr<int> weak){if(auto p= weak.lock())std::cout<<"\tobserve() is able to lock weak_ptr<>, value="<<*p<<'\n';elsestd::cout<<"\tobserve() is unable to lock weak_ptr<>\n";} int main(){std::weak_ptr<int> weak;std::cout<<"weak_ptr<> is not yet initialized\n"; observe(weak); {auto shared=std::make_shared<int>(42); weak= shared;std::cout<<"weak_ptr<> is initialized with shared_ptr\n"; observe(weak);} std::cout<<"shared_ptr<> has been destructed due to scope exit\n"; observe(weak);}
Output:
weak_ptr<> is not yet initialized observe() is unable to lock weak_ptr<>weak_ptr<> is initialized with shared_ptr observe() is able to lock weak_ptr<>, value=42shared_ptr<> has been destructed due to scope exit observe() is unable to lock weak_ptr<>
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 2316 | C++11 | lock() was not required to be atomic, but required to be noexcept, which led to a contradiction | specified to be atomic |
| checks whether the referenced object was already deleted (public member function)[edit] |