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.cpp
12345678910111213141516171819#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.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 5.56
Introduction to Weak Pointers
Scorri per mostrare il menu
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.cpp
12345678910111213141516171819#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.
Grazie per i tuoi commenti!