Skip to content

std::shared_ptr(C++11)

In a Nutshell

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

#include <memory>

Core API Quick Reference

OperationSignatureDescription
Constructionshared_ptr()Constructs a null pointer (default)
Construction (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 through the pointer
Reference countlong use_count() const noexceptReturns the number of shared_ptrs sharing the object
Boolean conversionexplicit operator bool() const noexceptChecks if it manages a non-null object
Swapvoid swap(shared_ptr& r) noexceptSwaps the managed objects of two shared_ptrs

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 Applicability: Medium

  • Internally maintains a control block and atomic reference count, incurring extra memory and CPU overhead
  • Copy operations are inherently thread-safe, making it suitable for sharing resources across tasks
  • Use with caution on MCUs with extremely limited RAM and Flash; prefer unique_ptr

Compiler Support

GCCClangMSVC
TBDTBDTBD

See Also


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

Built with VitePress