On this page
std::shared_ptr
Prev: std::make_unique | Up: memory | Next: std::weak_ptr
Rel: std::unique_ptr, std::weak_ptr
Ref: cppreference — std::shared_ptr
Tags: #public #prog #cpp #stdlib #memory #tier/standard
Overview
std::shared_ptr<T> (<memory>) provides reference-counted shared ownership across multiple owners. The managed object is destroyed when the last shared_ptr owning it is destroyed or reset. Reference count increments/decrements are thread-safe (atomic), though the pointee itself still needs synchronization if mutated concurrently.
Notes & Pitfalls
- Prefer
std::make_shared<T>(...): Allocates the control block and object in a single heap allocation. - Break reference cycles with
std::weak_ptr: Default tostd::unique_ptrunless ownership is genuinely shared.
Example
#include <cassert>
#include <memory>
int main() {
auto a = std::make_shared<int>(42);
auto b = a;
assert(a.use_count() == 2 && *b == 42);
}
Linked from
Related notes
- tuts/cpp/stdlib/memory/make_unique Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/stdlib/memory/unique_ptr Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/stdlib/memory/weak_ptr Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/stdlib/memory Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib
- tuts/cpp/stdlib/memory/auto_ptr shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/builtins/new_and_delete shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/builtins/sizeof_and_alignof shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier