Skip to content

std::shared_ptr (C++11)

In a Nutshell

Multiple smart pointers can share ownership of the same object. The object is automatically released only when the last owner is destroyed or reset.

#include <memory>

Core API Cheat Sheet

OperationSignatureDescription
Constructorshared_ptr()Constructs an empty pointer (default)
Constructor (Factory)template<class T, class... Args> shared_ptr<T> make_shared(Args&&... args)Allocates and constructs an object (C++11)
Resetvoid reset()Releases ownership of the currently managed object
Get Raw PointerT* get() const noexceptReturns the stored pointer
DereferenceT& operator*() const noexceptDereferences the stored pointer
Arrow OperatorT* operator->() const noexceptAccess members via pointer
Reference Countlong use_count() const noexceptReturns the number of shared_ptr owners sharing the object
Boolean Conversionexplicit operator bool() const noexceptChecks if a non-null object is managed
Swapvoid swap(shared_ptr& r) noexceptSwaps objects managed by two shared_ptr instances

Minimal Example

cpp
#include <iostream>
#include <memory>
struct Foo { Foo() { std::cout << "Foo()\n"; } ~Foo() { std::cout << "~Foo()\n"; } };
int main() {
    std::shared_ptr<Foo> p1 = std::make_shared<Foo>();
    std::shared_ptr<Foo> p2 = p1; // 引用计数变为 2
    std::cout << "count: " << p1.use_count() << "\n";
    p1.reset(); // count: 1
    p2.reset(); // 析构 Foo
}

Embedded Suitability: Medium

  • Maintains an internal control block and atomic reference counts, incurring extra memory and CPU overhead.
  • Copy operations are thread-safe, making it suitable for sharing resources between multiple tasks.
  • Use with caution on MCUs with extremely limited RAM and Flash; prefer unique_ptr where possible.

Compiler Support

GCCClangMSVC
TBDTBDTBD

See Also


Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05