What is Shared_ptr and Weak_ptr?
Table of Contents
A weak_ptr is created as a copy of shared_ptr. It provides access to an object that is owned by one or more shared_ptr instances but does not participate in reference counting. The existence or destruction of weak_ptr has no effect on the shared_ptr or its other copies.
The weak_ptr class template stores a “weak reference” to an object that’s already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.
The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.
What is a std :: Weak_ptr?
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. To prevent this, one of the pointers in the cycle can be made weak.
How is Weak_ptr implemented?
To implement weak_ptr , the “counter” object stores two different counters: The “use count” is the number of shared_ptr instances pointing to the object. The “weak count” is the number of weak_ptr instances pointing to the object, plus one if the “use count” is still > 0.
Can Weak_ptr be copied?
Throws: nothing. template weak_ptr(shared_ptr const & r); weak_ptr(weak_ptr const & r); template weak_ptr(weak_ptr const & r); Effects: If r is empty, constructs an empty weak_ptr; otherwise, constructs a weak_ptr that shares ownership with r as if by storing a copy of the pointer stored in r.
Why do we need weak_ptr?
std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not.
Should I use weak_ptr?
When cyclic references are unavoidable, or even preferable for some reason, use weak_ptr to give one or more of the owners a weak reference to another shared_ptr . A weak_ptr itself does not participate in the reference counting, and therefore, it cannot prevent the reference count from going to zero.
What is Shared_ptr?
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.