bhylu.com

Advertisements

C++ std::shared_ptr

Use a weak observer to avoid extending the lifetime of an object that several owners can retain.

How it works

std::shared_ptr keeps an object alive until its last shared owner releases it. This is useful when no single owner controls the complete lifetime, but reference counting has costs and can hide design problems. std::weak_ptr observes the control block without keeping the object alive; lock returns a temporary shared owner if it still exists. Strong-reference cycles can keep objects alive indefinitely, so relationship direction and observer roles need explicit design.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror shared-ownership.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · shared-ownership.cpp

#include <iostream>
#include <memory>

int main() {
    auto owner = std::make_shared<int>(9);
    std::weak_ptr<int> observer = owner;
    { auto temporary = observer.lock(); if (temporary) { std::cout << "Observed: " << *temporary << '\n'; } }
    owner.reset();
    std::cout << "Expired: " << observer.expired() << '\n';
}

Expected result

Observed: 9
Expired: 1

The temporary owner is destroyed before the original owner resets, so no strong reference remains afterwards. A lock-and-test pattern avoids using a target after it expires. Shared control-block operations do not make arbitrary reads and writes to the pointed-to object thread-safe. Prefer unique ownership unless sharing is actually part of the lifetime model.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.