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

Course Content

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. Advanced topics

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

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt