正常
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.
Header
#include <memory>
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Construct | shared_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) |
| Reset | void reset() | Releases ownership of the currently managed object |
| Get raw pointer | T* get() const noexcept | Returns the stored pointer |
| Dereference | T& operator*() const noexcept | Dereferences the stored pointer |
| Arrow access | T* operator->() const noexcept | Accesses members through the pointer |
| Reference count | long use_count() const noexcept | Returns the number of shared_ptr instances sharing the object |
| Boolean conversion | explicit operator bool() const noexcept | Checks whether it manages a non-null object |
| Swap | void swap(shared_ptr& r) noexcept | Exchanges 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_ptrinstead
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| TBD | TBD | TBD |
See Also
Some content is referenced from cppreference.com, licensed under CC-BY-SA 4.0