Skip to main content
Be Bitwise
C++Smart Pointers & Memory

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

cpp
#include <memory>
auto ptr = std::make_unique<int>(42);
std::cout << *ptr << std::endl; // 42
// No delete needed - ptr's destructor handles it

std::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:

cpp
auto a = std::make_unique<int>(42);
// auto b = a; // ERROR: cannot copy unique_ptr
auto b = std::move(a); // OK: transfer ownership
// a is now nullptr, b owns the int

Nothing 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.

Key Concept

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

cpp
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

cpp
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

cpp
// Transfer ownership into a function
void 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 transfer
void use_widget(const Widget &w) {
// Just read w, no ownership change
}
auto w2 = std::make_unique<Widget>("test2");
use_widget(*w2); // dereference to get reference

Rule 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.

Try itChange consume to take const Widget & and pass *w instead, then see when gamma dies.
C++ (GCC 9.2.0)