Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Introduction to Weak Pointers | Weak Pointers
C++ Smart Pointers

book
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.

cpp

main

copy
#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";
}
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.

question mark

If 10 shared pointers and 1 weak pointer reference a resource, what happens when all shared pointers go out of scope?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1
some-alt