Codectionary / Developer documentation / C++

C++ std::weak_ptr observers

C++11 weak_ptr observes shared ownership without extending the object lifetime. lock attempts to acquire a shared_ptr, returning an empty pointer when the object has already been destroyed.

Syntax

if (auto owner = observer.lock()) { /* use owner */ }

Examples

C++ std::weak_ptr observers

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <memory>
#include <iostream>
int main() {
    auto owner = std::make_shared<int>(42);
    std::weak_ptr<int> observer = owner;
    if (auto current = observer.lock()) std::cout << *current << '\n';
    owner.reset();
    std::cout << std::boolalpha << observer.expired() << '\n';
}
  1. Output: 42, then true. current leaves scope before owner is reset, so no strong owner remains.

Best practices

  • Use lock directly rather than checking expired and then assuming access is safe. Weak references can break shared_ptr ownership cycles.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading