Smart Pointers: Unique Pointers

In this lesson, we will examine the first type of smart pointer – the unique pointer. It limits access to its resource, thereby maintaining its privacy.

Introduction

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

std::unique_ptr exclusively takes care of its resource. It automatically releases the resource if it goes out of scope. No copy semantic is 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 is used.

Characteristics

Before you go into the usage of std::unique_ptr, we will present you 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 but although of an array of objects.
  • transparently offers the interface of the underlying resource.
  • can be parametrized with its own deleter function.
  • can be moved (move semantic).
  • can be created with the helper function std::make_unique.

Replacement for std::auto_ptr

⚠️ Don’t use std::auto_ptr
Classical C++98 has a smart pointer std::auto_ptr, which exclusively addresses the lifetime of a resource. std::auto_ptr has a conceptional issue. If you implicitly or explicitly copy an std::auto_ptr, the resource is moved. Therefore, rather than utilizing copy semantic, you have a hidden move semantic, leading to undefined behavior. So std::auto_ptr is deprecated in C++11 and removed in C++17. Instead, you should use std::unique_ptr. You can neither implicitly or explicitly copy a std::unique_ptr; you can only move it.

Get hands-on with 1000+ tech skills courses.