std::weak_ptr (3) - Linux Manuals
std::weak_ptr: std::weak_ptr
NAME
Synopsis
Defined in header <memory>
template< class T > class weak_ptr; (since C++11)
std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
Another use for std::weak_ptr is to break reference cycles formed by objects managed by std::shared_ptr. If such cycle is orphaned (i,e. there are no outside shared pointers into the cycle), the shared_ptr reference counts cannot reach zero and the memory is leaked. To prevent this, one of the pointers in the cycle can be made weak.
Member types
Member type Definition
element_type T (until C++17)
Member functions
constructor (public member function)
destructor (public member function)
operator= (public member function)
Modifiers
reset (public member function)
swap (public member function)
Observers
use_count (public member function)
expired (public member function)
lock (public member function)
owner_before (public member function)
Non-member functions
std::swap(std::weak_ptr) specializes the std::swap algorithm
(C++11)
Helper classes
std::atomic<std::weak_ptr> atomic weak pointer
(C++20)
Deduction_guides(since C++17)
Notes
Like std::shared_ptr, a typical implementation of weak_ptr stores two pointers:
* a pointer to the control block; and
* the stored pointer of the shared_ptr it was constructed from.
A separate stored pointer is necessary to ensure that converting a shared_ptr to weak_ptr and then back works correctly, even for aliased shared_ptrs. It is not possible to access the stored pointer in a weak_ptr without locking it into a shared_ptr.
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
LWG_3001 C++17 element_type was not updated for array support updated
Example
Demonstrates how lock is used to ensure validity of the pointer.
// Run this code