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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Can you explain how to use std::weak_ptr in code?
What happens if I try to access an object through a weak pointer after the shared pointers are gone?
Why would I use a weak pointer instead of a shared pointer?
Geweldig!
Completion tarief verbeterd naar 5.56
Introduction to Weak Pointers
Veeg om het menu te tonen
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.
Bedankt voor je feedback!