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 scopeunique 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 → deleteWATCH 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)copy vs move