Skip to content
C++

Smart Pointers Cheat Sheet

"Quick reference for unique_ptr, shared_ptr, and weak_ptr: syntax, operations, and when to use each."

Creation

cpp
// unique_ptr — prefer make_unique
auto u = std::make_unique<T>(args...);      // C++14
auto u = std::unique_ptr<T>(new T(args));   // avoid — use make_unique

// shared_ptr — prefer make_shared (one allocation)
auto s = std::make_shared<T>(args...);      // preferred
auto s = std::shared_ptr<T>(new T(args));   // two allocations — avoid

// weak_ptr — from shared_ptr
std::weak_ptr<T> w = s;

Transfer & sharing

cpp
// unique_ptr — move only
auto b = std::move(a);        // a is now null
fn(std::move(a));             // transfer to function

// shared_ptr — copy = shared ownership
auto c = s;                   // ref count +1
fn(s);                        // ref count +1, then -1 on return

// unique_ptr → shared_ptr (OK)
std::shared_ptr<T> sp = std::move(u);

// shared_ptr → unique_ptr (NOT possible)

Access

cpp
*p              // dereference (UB if null)
p->member       // member access (UB if null)
p.get()         // raw pointer (non-owning)
static_cast<bool>(p)  // true if not null
if (p) { }      // same

Release & reset

cpp
p.reset();            // delete owned object, p = null
p.reset(new T(...));  // delete old, own new
auto raw = p.release(); // give up ownership — you must delete

weak_ptr usage

cpp
if (auto locked = w.lock()) {
    locked->doWork();    // safe — object still alive
}
w.expired()             // true if no shared_ptr owners remain

Custom deleters

cpp
// unique_ptr with custom deleter
auto fp = std::unique_ptr<FILE, decltype(&fclose)>(
    fopen("f.txt", "r"), &fclose);

// shared_ptr with custom deleter (deleter not in type)
auto fp = std::shared_ptr<FILE>(fopen("f.txt", "r"), &fclose);

Array variants

cpp
auto arr = std::make_unique<int[]>(100);  // delete[] used
arr[0] = 42;
// No operator* or operator-> on T[] specialization

Size

cpp
sizeof(unique_ptr<T>)          // == sizeof(T*)   (with default deleter)
sizeof(shared_ptr<T>)          // == 2 * sizeof(void*)  (ptr + ctrl block ptr)
sizeof(weak_ptr<T>)            // == 2 * sizeof(void*)

Cheat card

unique_ptrshared_ptrweak_ptr
Owns object✓ exclusive✓ shared
Copyable
Runtime overhead0atomic inc/decatomic inc/dec
Extra memory0control blockptr to ctrl block
lock()
Use whendefaultshared lifetimeobserver / cycle break
Edit on GitHub