Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
218 字
1 分钟
Pointers

1. Features of Smart Pointers#

Smart pointers are C++ standard library objects that manage dynamically allocated memory automatically.

Main Features#

  • Automatic memory management (RAII) → Memory is released automatically when the smart pointer goes out of scope.
  • Prevents memory leaks → Eliminates the need for manual delete.
  • Ownership semantics → Clearly defines who owns an object.
  • Exception safety → Memory is freed even if an exception occurs.
  • Overloaded operators → Can be used like normal pointers (*, ->).
  • Part of the STL → Defined in <memory>.

2. When Would We Use Smart Pointers?#

Use smart pointers instead of raw pointers when:

  • Managing dynamically allocated objects
  • You want automatic lifetime management
  • Writing exception-safe code
  • Avoiding memory leaks and dangling pointers
  • Sharing ownership between objects (e.g., graphs, trees)
  • Following modern C++ best practices

📌 In modern C++, raw new and delete should be avoided in most application code.


3. Difference Between unique_ptr and shared_ptr#

Featureunique_ptrshared_ptr
OwnershipExclusive (only one owner)Shared (multiple owners)
Copyable❌ No✅ Yes
Movable✅ Yes✅ Yes
Reference counting❌ No✅ Yes
Memory overheadLowHigher (due to ref count)
PerformanceFasterSlightly slower
Use caseSingle owner resourceShared resource
Header<memory><memory>

Example#

#include <memory>
// unique_ptr
std::unique_ptr<int> p1 = std::make_unique<int>(10);
// std::unique_ptr<int> p2 = p1; // ❌ error
std::unique_ptr<int> p3 = std::move(p1); // ✅ ownership transferred
// shared_ptr
std::shared_ptr<int> s1 = std::make_shared<int>(20);
std::shared_ptr<int> s2 = s1; // ✅ shared ownership

One-Line Exam Summary#

  • Smart pointers automatically manage memory and prevent leaks.
  • Use unique_ptr when there is one owner.
  • Use shared_ptr when multiple owners need access to the same object.
Pointers
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/pointers/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00