Skip to content

本页便签全部 ↗

本页还没有便签

划选正文里的一段文字,点弹出的「✎ 存为便签」,回头在这里一键跳回原处。

std::shared_ptr (C++11) ​

In a Nutshell ​

Multiple smart pointers can jointly own the same object; the object is released automatically only when the last owner is destroyed or reset.

#include <memory>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructshared_ptr()Constructs an empty pointer (default)
Construct (factory)template<class T, class... Args> shared_ptr<T> make_shared(Args&&... args)Allocates and constructs the 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 accessT* operator->() const noexceptAccesses members through the pointer
Reference countlong use_count() const noexceptReturns the number of shared_ptr instances sharing the object
Boolean conversionexplicit operator bool() const noexceptChecks whether it manages a non-null object
Swapvoid swap(shared_ptr& r) noexceptExchanges the objects managed by two shared_ptr instances

Minimal Example ​

C++
#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; // reference count becomes 2
    std::cout << "count: " << p1.use_count() << "\n";
    p1.reset(); // count: 1
    p2.reset(); // destroys Foo
}

Embedded Suitability: Medium ​

  • Maintains an internal control block and an atomic reference count, which adds memory and CPU overhead
  • Copying itself is thread-safe, making it suitable for sharing resources across tasks
  • Use with caution on MCUs with extremely limited RAM and Flash; prefer unique_ptr instead

Compiler Support ​

GCCClangMSVC
TBDTBDTBD

See Also ​


Some content is referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.13.0-17-gf6158c6 · f6158c6 · 2026-11-20