Loading lessons...
Smart Pointers: unique_ptr
Smart Pointers: unique_ptr
A smart pointer is a pointer that cleans up after itself. std::unique_ptr owns its object and destroys it automatically when it leaves scope - no manual delete.
make_unique
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(5);
std::make_unique<int>(5) allocates a heap int (initialized to 5), and those pieces are wrapped in a unique_ptr. When p goes out of scope, the memory is freed on its own.
Use it like a pointer
cout << *p; // 5 - same dereference
*p = 6; // assign through the pointer
You use it just like a raw pointer, but you never call delete because the destructor handles it.
No copying, only moving
A unique_ptr is unique: two unique_ptrs cannot point to the same object.
std::unique_ptr<int> p1 = std::make_unique<int>(5);
std::unique_ptr<int> p2 = p1; // error: copying is not allowed
std::unique_ptr<int> p3 = std::move(p1); // ok: ownership moves
Copying is impossible, but you can move the ownership with std::move, transferring the unique from one pointer to another.
Why it deletes
The whole purpose is safety: if an exception is thrown or you return early, the unique_ptr still frees the memory during its scope cleanup. No leak, no double delete.
TL;DR
std::make_unique<int>(5)builds a smart pointer.unique_ptrfrees its object automatically at scope.- Use
*pjust like you would a raw pointer. - unique_ptr cannot be copied, only moved.
- It prevents leaks and double deletes for single owners.