Smart Pointers in C++

From the C++ cheat sheet · Smart Pointers & Move Semantics · verified Jul 2026

Smart Pointers

Owning pointers that free themselves.

cpp
// Quick Reference
#include <memory>
auto u = std::make_unique<int>(42);   // sole owner
auto s = std::make_shared<int>(42);   // ref-counted
std::weak_ptr<int> w = s;             // non-owning observer
💡 Default to unique_ptr (zero overhead); use shared_ptr only when ownership is truly shared.
⚡ Create with make_unique/make_shared - never new - for exception safety and clarity.
📌 unique_ptr is move-only: transfer ownership with std::move, you cannot copy it.
🟢 weak_ptr breaks shared_ptr reference cycles; lock() yields a shared_ptr if still alive.
smart-pointersmemory

More C++ tasks

Back to the full C++ cheat sheet