Course Content
C++ Smart Pointers
C++ Smart Pointers
Introduction to Weak Pointers
Smart pointer std::weak_ptr
doesn't own the object it points to. This essentially means that a weak pointer doesn't increase the reference count of the object.
A std::weak_ptr
allows access to an object managed by shared pointers without extending its lifetime. If all shared pointers go out of scope, the object is deleted, even if a weak pointer still exists. This is useful for observing shared objects without preventing their deallocation.
main
#include <iostream> #include <memory> struct Resource { Resource() { std::cout << "Resource created\n"; } ~Resource() { std::cout << "Resource destroyed\n"; } }; int main() { std::shared_ptr<Resource> sp1 = std::make_shared<Resource>(); std::weak_ptr<Resource> wp = sp1; // Weak pointer does not increase ref count std::cout << "Shared pointer going out of scope...\n"; sp1.reset(); // Resource is deleted if (wp.expired()) std::cout << "Resource no longer exists\n"; }
The Lifecycle of a Weak Pointer
Weak pointers are observers they can access an object but don't extend its lifetime.
Their lifecycle depends on shared pointers. When the last shared pointer is destroyed, the object is deallocated, and the weak pointer expires. It still exists but becomes empty.
Thanks for your feedback!