Search⌘ K

Unique Pointers

Explore the concept and usage of std::unique_ptr in C++. Discover how it automatically manages resource lifetimes with exclusive ownership, prevents memory leaks, and supports move semantics while replacing the deprecated auto_ptr. This lesson guides you through unique pointer methods, special deleters, and the advantages of using std::make_unique for safer and cleaner memory management.

Introduction

An std::unique_ptr automatically and exclusively manages the lifetime of its resource according to the RAII idiom. std::unique_ptr should be our first choice since it functions without memory or performance overhead.

std::unique_ptr exclusively controls its resource. It automatically releases the resource if it goes out of scope. No copy semantics are required, and it can be used in containers and algorithms of the Standard Template Library. std::unique_ptr is as cheap and fast as a raw pointer when no special delete function is used.

Characteristics

Before we go into the usage of std::unique_ptr, here are its characteristics in a few bullet points.

The std::unique_ptr:

  • can be instantiated with and without a resource.
  • manages the life cycle of a single object or an array of objects.
  • transparently offers the interface of the underlying resource.
  • can be parametrized with its own deleter
...