Skip to main content
Module 7 · Lesson 1 of 215/26 in the course~16 min
Module lessons (1/2)

std::unique_ptr and std::shared_ptr

Lesson preview5 hands-on exercises readyCourse C++ · Module 7 — Smart Pointers

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 / delete by managing the Heap via automatic RAII (<memory>).
  • Model exclusive property with std::unique_ptr (zero overhead) and transfer it with std::move.
  • Share resources on Heap with std::shared_ptr, preferring std::make_shared to 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

  1. 11. std::unique_ptr<T>: Exclusive Property at Zero Cost
  2. 22. Why std::make_unique / std::make_shared Are Safer than new
  3. 33. Interactive Simulator: Ownership, Reference Count & Move
  4. 44. Which Smart Pointer Should I Choose?
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 7 — Smart Pointers

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.