Skip to content

Beginning of the lesson

Smart Pointers

Automatic, exception-safe ownership for heap objects

Big Idea: A smart pointer is a small stack object that owns a heap allocation and frees it automatically the moment ownership ends. Instead of pairing every new with a matching delete by hand, you let the pointer's destructor do it for you. This is RAII (Resource Acquisition Is Initialization) applied to memory: the lifetime of a resource is tied to the lifetime of an object on the stack.
By the end you will be able to:
  • explain why raw new/delete is fragile,
  • use std::unique_ptr for exclusive ownership and move it around,
  • use std::shared_ptr for shared ownership and read its reference count,
  • use std::weak_ptr to observe without owning and to break reference cycles.

1. The problem with raw new / delete

You already know how to allocate on the heap with new and release with delete. The trouble is that you become responsible for the delete, and there are many ways to get it wrong:

  • Leak: you forget the delete, or an early return skips it, and the memory is never returned.
  • Dangling pointer: you delete and keep using the pointer.
  • Double free: two code paths both delete the same object.
  • Exception leak: an exception is thrown between new and delete, so the delete never runs.
void process() {
    Widget* w = new Widget();   // manual allocation
    if (!w->load())
        return;                 // BUG: leaks w, delete never runs
    w->run();
    delete w;                   // easy to forget, or skip via exception
}

Smart pointers remove this whole class of bugs by making the compiler and the destructor responsible for cleanup. Because a smart pointer is a stack object, its destructor runs automatically at the end of the scope, on every path, including when an exception unwinds the stack.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers