std::unique_ptr
std::unique_ptr is the workhorse smart pointer in modern C++. It takes ownership of a heap allocation and quietly cleans it up the moment the unique_ptr goes out of scope.
Basic Usage
#include <memory>
auto ptr = std::make_unique<int>(42);std::cout << *ptr << std::endl; // 42// No delete needed - ptr's destructor handles itstd::make_unique<T>(args...) heap-allocates a T and wraps it for you. Prefer it over raw new. Always.
Unique Ownership
A unique_ptr cannot be copied:
auto a = std::make_unique<int>(42);// auto b = a; // ERROR: cannot copy unique_ptrauto b = std::move(a); // OK: transfer ownership// a is now nullptr, b owns the intNothing on the heap moves. The move copies the pointer value into b and writes null into a:
When both go out of scope, b deletes the int and a's destructor sees null and does nothing, so the allocation is freed exactly once.
unique_ptr enforces single ownership at compile time. Exactly one owner, ever. When ownership transfers via std::move, the source goes null. Double-free bugs become unrepresentable.
With Custom Types
class Widget { std::string name;public: Widget(const std::string &n) : name(n) { std::cout << "Widget " << name << " created" << std::endl; } ~Widget() { std::cout << "Widget " << name << " destroyed" << std::endl; }};
void example() { auto w = std::make_unique<Widget>("alpha"); // Widget alpha destroyed - when w goes out of scope}Polymorphism with unique_ptr
class Shape {public: virtual double area() const = 0; virtual ~Shape() = default;};
class Circle : public Shape { double radius;public: Circle(double r) : radius(r) {} double area() const override { return 3.14159 * radius * radius; }};
std::vector<std::unique_ptr<Shape>> shapes;shapes.push_back(std::make_unique<Circle>(5.0));Passing unique_ptr
// Transfer ownership into a functionvoid take_ownership(std::unique_ptr<Widget> w) { // w is destroyed when this function returns}
auto w = std::make_unique<Widget>("test");take_ownership(std::move(w)); // explicit move required
// Borrow without ownership transfervoid use_widget(const Widget &w) { // Just read w, no ownership change}
auto w2 = std::make_unique<Widget>("test2");use_widget(*w2); // dereference to get referenceRule of thumb: pass unique_ptr by value only when ownership is changing hands. Otherwise hand over a reference to the underlying object.
Here's the whole life story of a few Widgets: built by a factory, moved into a vector, borrowed, handed off to a function. Before you run it, predict where each "destroyed" line will appear.