C++20 sections · 1024 units
Open in Course

Introduction to Smart Pointers

Automatic cleanup

Smart pointers are class templates that wrap raw pointers and manage deletion automatically. They use RAII: the destructor calls delete, so memory is freed when the smart pointer leaves scope.

The standard library provides three: unique_ptr for exclusive ownership, shared_ptr for shared ownership with reference counting, and weak_ptr to break circular references. Include to use them.

Smart pointers work with any type: unique_ptr, shared_ptr<int[]>. They're the modern C++ way to handle dynamic memory safely.