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.
Use make_unique
Section titled “Use make_unique”C++ Core Guideline: R.23: Use make_unique() to make unique_ptrs
make_uniquegives a more concise statement of the construction. It also ensures exception safety in complex expressions (in pre-C++17 code).
Avoid usage with arrays
Section titled “Avoid usage with arrays”From Effective Modern C++:
The existence of
std::unique_ptrfor arrays should be of only intellectual interest to you, becausestd::array,std::vector,std::stringare virtually always better data structure choices than raw arrays. About the only situation I can conceive of when astd::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 callsdelete.- For arrays, you must use
std::unique_ptr<T[]>, which callsdelete[].
Copy semantics
Section titled “Copy semantics”unique_ptr is non-copyable by design. Attempting to copy will not compile.
Use std::move to transfer ownership.
Resource requirements
Section titled “Resource requirements”The managed type must be complete at the point of deletion, otherwise the destructor is undefined behavior.
Custom deleters
Section titled “Custom deleters”Custom deleters change the type of the unique_ptr. This adds a storage cost the to object.
Resources
Section titled “Resources”- std::unique_ptr on cppreference.com