Module lessons (1/2)
std::unique_ptr and std::shared_ptr
Guarantee exclusive ownership with unique_ptr + std::move or shared with reference counting via shared_ptr.
What you'll learn in this lesson
- Eliminate manual
new/deleteby managing the Heap via automatic RAII (<memory>). - Model exclusive property with
std::unique_ptr(zero overhead) and transfer it withstd::move. - Share resources on Heap with
std::shared_ptr, preferringstd::make_sharedto reduce fragmentation and allocations.
Overview
In modern C++ there is a golden rule: never write new or delete in your application code. The smart pointers of the <memory> header encapsulate the raw pointer inside an object on the Stack whose destructor calls delete in an automatic deterministic way.
std::unique_ptr represents a sole owner. It takes up exactly as much memory as a raw pointer (8 bytes on 64-bit) and generates the same machine code as new/delete, but it is not copyable (to prevent double-free): it can only be moved via std::move:
Sections covered in this lesson
- 11.
std::unique_ptr<T>: Exclusive Property at Zero Cost - 22. Why
std::make_unique/std::make_sharedAre Safer thannew - 33. Interactive Simulator: Ownership, Reference Count & Move
- 44. Which Smart Pointer Should I Choose?
- 5Practical exercises
- 6Check for understanding
Unlock "std::unique_ptr and std::shared_ptr" and the full Course C++ curriculum
Guarantee exclusive ownership with unique_ptr + std::move or shared with reference counting via shared_ptr.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.