Implement std::weak_ptr<T>

C++
Author

Quasar

Published

March 20, 2026

Introduction

The role of the weak_ptr is to model the temporary ownership of T. The type weak_ptr<T> is meant to interact with the shared_ptr<T> in a way that makes the continued existence of the pointee testable from the client code.

An example of weak_ptr usage, inspired by the excellent cppreference website is as follows:

#include <format>
#include <iostream>
#include <memory>

void observe(std::weak_ptr<int> w) {
    if (std::shared_ptr<int> sh = w.lock())
        std::cout << std::format("*sh = {}\n", *sh);
    else
        std::cout << "w is expired";
}

int main() {
    std::weak_ptr<int> w;

    {
        auto sh = std::make_shared<int>(3);
        w = sh;  // weak_ptr made from shared_ptr
        // w points to a live shared_ptr<int> here
        observe(w);
    }
    // w points to an expired shared_ptr<int> here
    observe(w);
}

As this example shows, you can make a weak_ptr<T> from a shared_ptr<T>, but a weak_ptr does not own the resource until you call lock() on it, yielding shared_ptr<T>, from which you can safely use the resource after having verified that it does not model an emppty pointer.