“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

Smart pointers: ownership in the type

Learn

Lesson 7 of 7 standard ~6 min

Smart pointers are RAII and move semantics fused into a single tool. A unique_ptr is a RAII wrapper that owns a heap object and frees it in its destructor; its move-only nature encodes unique ownership directly in the type system, so the compiler catches ownership mistakes for you.

See how move semantics shows up as a compile error you actually want.

standardMultiple choice

What happens here?

auto a = std::make_unique<int>(5);
std::unique_ptr<int> b = a;   // <-- this line
Go deeper ↓Ownership by diff

And the idiom for creating one — there is a reason it is not just new.

standardMultiple choice

Why prefer std::make_unique<T>(args...) over std::unique_ptr<T>(new T(args...))?

Go deeper ↓Ownership by diff