Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::weak_ptr — observation without extending object lifetime

std::weak_ptr<T> observes an object managed by std::shared_ptr without keeping it alive. Its lock() member obtains a temporary shared owner or an empty std::shared_ptr if ownership has already expired.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <memory>
std::weak_ptr<T> observer = owner;
if (auto held = observer.lock()) {
    // Access the object through held.
}

std::weak_ptr<T>, declared in <memory>, stores a weak reference associated with ownership managed by std::shared_ptr. It does not increase the number of strong owners or extend the object's lifetime. Construct it from a compatible std::shared_ptr or leave it empty.

It provides neither * nor ->. Call lock() and check the returned std::shared_ptr. Acquiring shared ownership is atomic: the method returns a shared owner or an empty pointer if ownership has expired, without throwing exceptions. Keep the result alive throughout access to the object.

expired() means use_count() == 0; use_count() counts strong owners, not observers. Checking expired() alone does not reserve the lifetime: another thread can release the last owner before a later lock(). The atomicity of lock() does not synchronize access to the object's data.

Weak references are useful for observation and breaking ownership cycles: a back-reference can use std::weak_ptr instead of another strong owner. reset() empties the observer without destroying the observed object. The example uses facilities available in C++23; the supplied current working draft also contains later extensions.

Examples

#include <iostream>
#include <memory>

int main() {
    std::weak_ptr<int> observer;
    {
        auto owner = std::make_shared<int>(42);
        observer = owner;
        if (auto held = observer.lock()) {
            std::cout << *held << '\n';
        }
    }
    std::cout << std::boolalpha << observer.expired() << '\n';
    std::cout << static_cast<bool>(observer.lock()) << '\n';
}

Result

42
true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources