weak_ptr
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. It is required in some cases to break circular references between shared_ptr instances.
Cyclic Dependency (Problems with shared_ptr): Let’s consider a scenario where we have two classes A and B, and both have pointers to other classes. So, it’s always like A is pointing to B and B is pointing to A. Hence, use_count will never reach zero and they never get deleted.
This is the reason we use weak pointers(weak_ptr) as they are not reference counted. So, the class in which weak_ptr is declared doesn’t have a stronghold over it i.e. the ownership isn’t shared, but they can have access to these objects.
So, in the case of shared_ptr because of cyclic dependency use_count never reaches zero which is prevented by using weak_ptr, which removes this problem by declaring A_ptr as weak_ptr, thus class A does not own it, only has access to it and we also need to check the validity of object as it may go out of scope. In general, it is a design issue.
auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++
Prerequisite – Smart Pointers
Smart Pointer is a pointer-wrapping stack-allocated object. Smart pointers, in plain terms, are classes that wrap a pointer, or scoped pointers.
C++ libraries provide implementations of smart pointers in the following types:
- auto_ptr
- unique_ptr
- shared_ptr
- weak_ptr
They all are declared in a memory header file( #include<memory>) which is used to manage dynamic memory allocation.