C++ Smart Pointers Cheat Sheet
Covers unique_ptr, shared_ptr, and weak_ptr semantics, ownership models, custom deleters, and how to avoid reference-cycle memory leaks.
2 PagesIntermediateApr 12, 2026
std::unique_ptr
Exclusive ownership smart pointer with zero overhead.
cpp
#include <memory>std::unique_ptr<int> p = std::make_unique<int>(42); // preferred over newstd::cout << *p;std::unique_ptr<int> p2 = std::move(p); // ownership transferred, p is now null// std::unique_ptr<int> p3 = p2; // compile error: copying is disabledvoid takeOwnership(std::unique_ptr<int> ptr) { /* ... */ }takeOwnership(std::move(p2)); // must move, cannot copy// custom deleterstd::unique_ptr<FILE, decltype(&fclose)> file(fopen("f.txt", "r"), &fclose);
std::weak_ptr
Non-owning observer of a shared_ptr that breaks reference cycles.
cpp
std::shared_ptr<int> sp = std::make_shared<int>(99);std::weak_ptr<int> wp = sp; // does not increase use_countif (auto locked = wp.lock()) { // returns a shared_ptr, or nullptr if expired std::cout << *locked;} else { std::cout << "expired";}std::cout << wp.expired(); // true if the managed object was already destroyed
Avoiding Cyclic References
Break shared_ptr reference cycles that leak memory.
cpp
struct Node { std::shared_ptr<Node> next; std::weak_ptr<Node> prev; // weak_ptr breaks the cycle};auto a = std::make_shared<Node>();auto b = std::make_shared<Node>();a->next = b;b->prev = a; // if this were shared_ptr, a and b would leak forever
Smart Pointer Comparison
When to reach for each smart pointer type.
- unique_ptr- Sole owner, move-only, no runtime overhead versus a raw pointer; the default choice.
- shared_ptr- Multiple owners via atomic reference counting; has overhead from the control block.
- weak_ptr- Non-owning reference to a shared_ptr-managed object; used to break cycles or observe without extending lifetime.
- make_unique / make_shared- Preferred factory functions; exception-safe and, for shared_ptr, allocate object + control block in one block.
- Raw pointer- Still fine for non-owning, non-nullable observation where lifetime is guaranteed by the caller.
Pro Tip
Never construct two independent shared_ptrs from the same raw pointer - each gets its own control block and the object gets double-deleted; always copy an existing shared_ptr instead of wrapping the same raw pointer twice.
Was this cheat sheet helpful?
Explore Topics
#CSmartPointers#CSmartPointersCheatSheet#Programming#Intermediate#StdUniquePtr#StdSharedPtr#StdWeakPtr#AvoidingCyclicReferences#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance