DevAcademia lesson/C++ Modern Essentials
C++ Smart Pointers
Topic progressTopic 103 of 109 - 94% complete
~12 min lesson11 learning blocks2 code examples1 checks/interactions
Lesson outline
Why Smart Pointers?
Raw owning pointers with new/delete are error-prone: forget delete and you leak; delete twice and you crash. Smart pointers in own a resource and free it automatically when they go out of scope (RAII).
std::unique_ptr - Exclusive Ownership
A unique_ptr owns its object alone and frees it automatically. Create it with std::make_unique (C++14).
std::shared_ptr - Shared Ownership
A shared_ptr keeps a reference count; the object is freed when the last owner is destroyed. Create it with std::make_shared.
| unique_ptr | shared_ptr | |
|---|---|---|
| Ownership | Exclusive (one owner) | Shared (reference-counted) |
| Copyable | No (move-only) | Yes |
| Overhead | None beyond a raw pointer | Atomic reference count |
| Create with | std::make_unique | std::make_shared |
Was this topic clear?