std::unique_ptr#include <memory> is a smart pointer with sole ownership of its managed object. It is available from the memory header:
#include <memory>
{
int* raw = new int(5);
std::unique_ptr#include <memory><int> p(raw); // Give p ownership of raw.
*p; // 5
}
// p is destroyed and deletes the raw pointer.It behaves like a raw pointer:
std::unique_ptr#include <memory><std::string#include <string>> s(new std::string#include <string>("hello"));
*s; // "hello"
s->size(); // 5
s == nullptr; // falsestd::unique_ptr#include <memory> cannot be copied but it can be moved:
std::unique_ptr#include <memory><int> a(new int(5));
std::unique_ptr#include <memory><int> b = a; // ERROR.
std::unique_ptr#include <memory><int> c = std::move#include <utility>(a); // OK, c owns the int and a is empty.Other common methods:
p.get(); // Returns the raw pointer without giving up ownership.
p.reset(); // Deletes the object and makes p empty.
p.release(); // Gives up ownership and returns the raw pointer, which the caller must delete.std::unique_ptr#include <memory> can own an array and calls delete[] on it:
std::unique_ptr#include <memory><int[]> arr(new int[10]);
arr[0] = 1;Note
A std::unique_ptr#include <memory> (with the default deleter) is the same size as a raw pointer and has no runtime overhead. Prefer std::unique_ptr#include <memory> over a raw pointer.
std::make_unique#include <memory>() creates the object and the std::unique_ptr#include <memory> in one call, without writing new:
auto p = std::make_unique#include <memory><int>(5);
auto s = std::make_unique#include <memory><std::string#include <string>>("hello");
auto arr = std::make_unique#include <memory><int[]>(10);Note
Prefer std::make_unique#include <memory>() over new, so nothing can leak.
Dan