C++C++ Explainer
C++ · 3 · Memory & Smart Pointers11 / 36 · 31%

unique_ptr & shared_ptr

Prefer smart pointers over raw new/delete. Ownership becomes visible.

shortcuts: ← prev · → next · M mark
1

unique_ptr

Sole owner. Non-copyable, movable. Zero overhead.

Example
example
#include <memory>
auto p = std::make_unique<int>(42);
std::cout << *p;
// no delete — destructor runs when p goes out of scope
shared_ptr<T>ptr, ctrlcontrol block · ref=2T on heap
unique ownership
2

shared_ptr

Reference-counted shared ownership. Slightly more expensive.

Example
example
auto a = std::make_shared<int>(7);
auto b = a;         // ref count = 2
// both go out of scope → delete
WATCH OUT
Two shared_ptrs pointing at each other = leak. Break cycles with weak_ptr.
3

Move Semantics

std::move casts to rvalue so the resource is stolen, not copied.

Example
example
std::vector<int> a(1000000, 1);
std::vector<int> b = std::move(a); // O(1) steal, not O(n) copy
// a is now valid-but-unspecified (empty in practice)
COPYsrc [1,2,3]dst [1,2,3]MOVEsrc (empty)dst [1,2,3]move steals the buffer — no allocation
copy vs move