CKTIS / C++
std::shared_ptr — shared ownership
std::shared_ptr<T> from <memory> shares ownership of an object. Copies keep it alive, and releasing the last owner triggers cleanup. std::weak_ptr observes the object without extending its lifetime.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <memory>
std::shared_ptr<T> p = std::make_shared<T>(args...);
std::shared_ptr<T> q = p;
p.reset();std::shared_ptr<T> from <memory> represents shared ownership. Copying shares the object rather than copying it. reset() releases one owner's share; the last owner triggers deletion of the managed object or the appropriate deleter. get() only exposes the stored pointer—it does not transfer ownership.
Create an object with std::make_shared<T>(args...), which forwards arguments to its constructor. Do not construct an independent std::shared_ptr from p.get(): this creates a separate ownership group and can cause double deletion. Before dereferencing, ensure the stored pointer points to a live object.
Cycles of strong references can keep objects alive indefinitely. Break a cycle with std::weak_ptr, which does not extend the object's lifetime. lock() returns a std::shared_ptr that shares ownership if the observed ownership group still has at least one shared owner. If the group has expired, lock() returns an empty std::shared_ptr even if the object is still alive, for example because the deleter does nothing.
Safe ownership bookkeeping does not synchronize the object's data. Different instances sharing ownership can be operated on concurrently; modifying the same instance requires synchronization, such as std::atomic<std::shared_ptr<T>>. Access to the object itself needs separate protection when a data race is possible. use_count() is not a synchronization mechanism.
The example shows that q keeps the object alive after p.reset(), and the observer expires after the block ends. This entry targets C++23; the supplied working draft is updated and may contain later features. A repository compiler flag does not attest the production runtime.
Examples
#include <iostream>
#include <memory>
int main() {
auto p = std::make_shared<int>(42);
std::weak_ptr<int> observer = p;
{
std::shared_ptr<int> q = p;
p.reset();
std::cout << *q << '\n';
std::cout << std::boolalpha << observer.expired() << '\n';
}
std::cout << observer.expired() << '\n';
}
Result
42 false true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.