Skip to content

unique_ptr

Wraps a raw pointer with RAII to manage the lifetime of the pointed-to object.
Ownership is exclusive, only one unique_ptr can own a given resource at a time.

C++ Core Guideline: R.23: Use make_unique() to make unique_ptrs

make_unique gives a more concise statement of the construction. It also ensures exception safety in complex expressions (in pre-C++17 code).

From Effective Modern C++:

The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, std::string are virtually always better data structure choices than raw arrays. About the only situation I can conceive of when a std::unique_ptr<T[]> would make sense would be when you’re using a C-like API that returns a raw pointer to a heap array that you assume ownership of.

However, it can be argued that std::unique_ptr<T[]> is suitable in situations where memory and initialization overhead needs to be strictly minimized. In these situations, be aware that:

  • std::unique_ptr<T> assumes a single object and calls delete.
  • For arrays, you must use std::unique_ptr<T[]>, which calls delete[].

unique_ptr is non-copyable by design. Attempting to copy will not compile.
Use std::move to transfer ownership.

The managed type must be complete at the point of deletion, otherwise the destructor is undefined behavior.

Custom deleters change the type of the unique_ptr. This adds a storage cost the to object.