On this page
  1. std::weak_ptr
  2. Overview
  3. Notes & Pitfalls
  4. Example

std::weak_ptr

Prev: std::shared_ptr | Up: memory | Next: std::auto_ptr (Removed)
Rel: std::shared_ptr, Memory Management Models
Ref: cppreference — std::weak_ptr
Tags: #public #prog #cpp #stdlib #memory #tier/specialized


Overview

std::weak_ptr<T> (<memory>) holds a non-owning reference to an object managed by std::shared_ptr<T> without incrementing the strong reference count. It is primarily used to break parent↔child reference cycles and build non-owning caches/observers.

Notes & Pitfalls

Example

#include <cassert>
#include <memory>

int main() {
    std::weak_ptr<int> wp;
    {
        auto sp = std::make_shared<int>(7);
        wp = sp;
        if (auto locked = wp.lock()) assert(*locked == 7);
    }
    assert(wp.expired());
}

Linked from

Related notes