Smart Pointers#

Summary based on C++ Primer, 5th ed. Chapter 12 (Dynamic Memory and Smart Pointers).

1. Why Smart Pointers Exist (RAII and Ownership)#

  • Stack vs. Heap Lifetimes: Stack local variables automatically invoke their destructor (~Class()) when leaving scope ({ ... }), whereas heap memory allocated via new is NOT automatically freed when a raw pointer (T*) goes out of scope, leading to memory leaks.
  • RAII (Resource Acquisition Is Initialization): By wrapping a raw pointer (T*) inside a stack-allocated wrapper class whose destructor (~SmartPtr()) automatically calls delete ptr;, heap memory is deterministically freed when the wrapper leaves scope.
  • The Copy / Double-Free Problem and Ownership Models: If two smart pointers pointed to the same heap address and both called delete in their destructors, a fatal Double Free crash would occur. To solve this, C++11 <memory> provides three smart pointers with distinct ownership semantics:
Smart PointerOwnership ModelCopyable?*ptr / ptr-> DereferenceKey Characteristics & Use Case
std::unique_ptr<T>Exclusive Ownership — 1:1❌ std::move only✅Zero overhead with the same size and speed as T*; the default choice for dynamic memory.
std::shared_ptr<T>Shared Ownership — N:1✅ updates use_count✅Calls delete only when the strong reference count use_count in the Control Block reaches 0.
std::weak_ptr<T>Non-Owning — Observer✅ use_count unchanged❌ .lock() requiredObserves a shared_ptr-managed object without incrementing use_count, breaking circular reference memory leaks.

2. std::unique_ptr: Exclusive Ownership and std::make_unique#

Because only one unique_ptr can own a given object at a time, its copy constructor and copy-assignment operator are deleted (= delete).

  • Creation: Prefer std::make_unique<T> (introduced in C++14) over raw new.
  • Ownership Transfer: Copying is prohibited; ownership can only be transferred via std::move.
#include <memory>

// Recommended: Create via std::make_unique<T> instead of raw new
auto up1 = std::make_unique<std::string>("hello");

// auto up2 = up1;         // ❌ Compile error: cannot copy exclusive ownership
auto up2 = std::move(up1); // ✅ Valid: transfers ownership from up1 to up2 (up1 becomes nullptr)

// Dereference using * and -> just like a raw pointer
*up2 = "world";
size_t len = up2->size();

// Supports dynamic arrays and automatically calls delete[] upon destruction
auto arr = std::make_unique<int[]>(10); // Length 10, all elements 0 (equivalent to new int[10]())

How unique_ptr Works Under the Hood (get, release, reset)#

std::unique_ptr<T> is not magic, it is simply a thin RAII wrapper class holding a single raw pointer member variable (T* ptr_). Looking at its simplified implementation makes what get(), release(), and reset() actually do immediately obvious:

template <typename T>
class unique_ptr {
private:
    T* ptr_ = nullptr; // The sole member variable holding the heap address

public:
    // Constructor: takes a raw pointer and stores it in ptr_ (acquires ownership)
    explicit unique_ptr(T* p = nullptr) noexcept : ptr_(p) {}

    // Destructor: automatically deletes ptr_ when leaving scope
    // Note: In C++, delete nullptr; is guaranteed to be a safe no-op
    ~unique_ptr() noexcept {
        delete ptr_;
    }

    // 1. get(): simply returns the stored address without modifying ptr_
    T* get() const noexcept {
        return ptr_;
    }

    // 2. release(): sets ptr_ = nullptr without calling delete, and returns the old address
    //    -> When ~unique_ptr() later runs, it executes delete nullptr; which is a no-op
    T* release() noexcept {
        T* old_ptr = ptr_;
        ptr_ = nullptr;
        return old_ptr;
    }

    // 3. reset(): immediately deletes old_ptr and replaces ptr_ with new_ptr
    //    -> Calling up.reset() with no arguments sets ptr_ = nullptr and destroys the old object early
    void reset(T* new_ptr = nullptr) noexcept {
        T* old_ptr = ptr_;
        ptr_ = new_ptr;
        delete old_ptr;
    }
};
  • Why Is the unique_ptr(T* p) Constructor noexcept? — Separation from make_unique:

    • The unique_ptr constructor itself never allocates heap memory; heap allocation happens beforehand inside new or the std::make_unique helper function. For Args&&... and ... pack expansion syntax, see Templates: Variadic Templates:
      template <typename T, typename... Args>
      unique_ptr<T> make_unique(Args&&... args) {    // NOT noexcept: inner new can throw std::bad_alloc
          T* p = new T(std::forward<Args>(args)...); // Heap allocation completes before entering unique_ptr's constructor
          return unique_ptr<T>(p);                   // Passes only the already-allocated address p
      }
    • Any std::bad_alloc is thrown while evaluating new before unique_ptr(T* p) is ever entered. Inside unique_ptr(T* p), 0 heap allocations occur — it merely copies the pointer p into ptr_, guaranteeing noexcept.
  • When to use each method:

    1. .get() — Borrowing the address: Use when passing the pointer to a function void Print(const Foo* f) that only reads or inspects the object without taking ownership: Print(up.get()).
    2. .release() — Detaching ownership without deleting the heap object: Use when you need unique_ptr to stop auto-deleting the object so you can hand the raw pointer off to a legacy C API or another wrapper that will delete it.
    3. .reset(...) — Immediately deleting or replacing the heap object: Call up.reset() to destroy the heap object early before the scope ends, or up.reset(new Foo()) to delete the existing object and take ownership of a new one.

Three Ownership Rules When Interacting with Raw Pointers T*#

Based on when ptr_ is deleted above, whenever you pass or receive a raw pointer T*, track who holds ownership — the responsibility to call delete:

MethodDeletes Existing Heap Object? & BehaviorOwnership TransferMandatory Caller Rule
.reset(RAW_PTR)
unique_ptr<T>(RAW_PTR)
Immediately calls delete on any previously managed object, then acquires ownership of RAW_PTRCaller → unique_ptrImmediately give up ownership of RAW_PTR. Never manually delete it or pass it to another smart pointer, or a Double Free occurs.
.get()Does not call delete — unique_ptr retains ownership and returns the internal T* address for observation onlyNoneNever delete the returned pointer or wrap it in another smart pointer, or a Double Free occurs.
.release()Does not call delete — sets the internal pointer to nullptr to relinquish ownership and returns the live T* addressunique_ptr → CallerAlways take ownership of the returned pointer. Pass it to another smart pointer or manually delete it, or a memory leak occurs.
// 1. Constructor / .reset(): ownership moves into unique_ptr -> never delete raw outside
int* raw = new int(10);
std::unique_ptr<int> up(raw);
// delete raw; // ❌ Forbidden: causes Double Free when up is destroyed

// 2. .get(): borrows the raw address without transferring ownership -> never delete or re-wrap
int* borrowed = up.get();
// delete borrowed;                    // ❌ Forbidden: Double Free
// std::unique_ptr<int> bad(borrowed); // ❌ Forbidden: two unique_ptrs now own the same address

// 3. .release(): up becomes nullptr without deleting -> caller MUST take ownership
int* released = up.release(); // up is now nullptr and ~unique_ptr() will NOT delete it
delete released;              // ✅ Safe: must manually delete or transfer to another owner to prevent a leak

3. std::shared_ptr: Control Block and std::make_shared#

Because multiple shared_ptr instances across independent scopes must share the exact same use_count in real time, the reference count cannot live inside an individual stack variable — it must reside in a separate heap-allocated Control Block. Accordingly, a shared_ptr internally holds two pointers: the object pointer (T*) and a Control Block pointer. When the last shared_ptr is destroyed and use_count reaches 0, the managed object is automatically deleted.

  • Why shared_ptr(T* p) Is NOT noexcept Unlike unique_ptr(T* p):
    • When constructing shared_ptr<int> sp(new int(42));, new int(42) allocates only the int beforehand; inside shared_ptr(T* p)’s constructor, a second heap allocation (new ControlBlock) must be performed.
    • Because allocating the Control Block can throw std::bad_alloc, shared_ptr(T* p) cannot be noexcept (if Control Block allocation fails, the constructor catches the exception, calls delete p; to prevent leaking p, and rethrows).
    • Conversely, std::make_shared<T> allocates a single contiguous block holding both T and the ControlBlock in 1 heap allocation, cutting allocation overhead in half and improving cache locality.
Call TargetHeap Allocations Inside the FunctionTotal Heap Allocationsnoexcept?
unique_ptr<T>(p) constructor0 — copies already-allocated address p1 (outer new)✅
std::make_unique<T>1 (new T)1❌ can throw bad_alloc
shared_ptr<T>(p) constructor1 (new ControlBlock)2 (outer new + Control Block)❌ can throw bad_alloc
std::make_shared<T>1 (combined T + ControlBlock)1❌ can throw bad_alloc
// Recommended: Prefer std::make_shared<T> over raw new
{
    auto sp1 = std::make_shared<std::string>(10, '9'); // Single allocation for object + Control Block, use_count == 1
    {
        auto sp2 = sp1; // Shares existing Control Block pointer and increments use_count: 1 -> 2 — 0 allocations, noexcept
        std::cout << *sp2 << " (" << sp2->size() << ")\n"; // Dereference via * and ->
    } // sp2 leaves scope, decrementing use_count: 2 -> 1 — not 0 yet, so object remains alive
} // sp1 leaves scope, decrementing use_count: 1 -> 0 and automatically freeing heap memory!

4. std::weak_ptr: Breaking Circular References and lock()#

1. How Circular Reference Memory Leaks Happen#

If two objects reference each other using shared_ptr, their reference counts remain stuck at 1 even after all external variables go out of scope, leaking both objects forever:

struct Node {
    std::shared_ptr<Node> next;
    std::shared_ptr<Node> prev; // Cause of leak: both directions use strong references (shared_ptr)!
};

void circular_leak_example() {
    auto spA = std::make_shared<Node>(); // 1. spA points to Node A -> [Node A use_count = 1]
    auto spB = std::make_shared<Node>(); // 2. spB points to Node B -> [Node B use_count = 1]

    spA->next = spB; // 3. Both spB and spA->next point to Node B -> [Node B use_count = 2]
    spB->prev = spA; // 4. Both spA and spB->prev point to Node A -> [Node A use_count = 2]
} // 5. Function ends: spA and spB are destroyed, but both nodes remain at use_count == 1 (memory leak!)

Why neither node is freed when the function exits (Step 5):

  • Node A’s use_count (2 → 1): Local variable spA is destroyed, but spB->prev still holds a strong reference to Node A.
  • Node B’s use_count (2 → 1): Local variable spB is destroyed, but spA->next still holds a strong reference to Node B.
  • Because neither reference count reaches 0, both objects are leaked on the heap forever.

2. Breaking the Cycle with std::weak_ptr and lock()#

Changing one direction (e.g., prev) to std::weak_ptr<Node> does not increment use_count, allowing both nodes’ use_count to reach 0 cleanly when spA and spB leave scope.

Because a weak_ptr does not own the object, the target may have already been destroyed. Therefore, weak_ptr cannot be directly dereferenced (*wp and wp-> do not exist). You must call wp.lock() to check whether the object still exists and obtain a temporary shared_ptr:

  • If the target object is still alive (use_count >= 1): wp.lock() returns a valid std::shared_ptr<T> and increments use_count by +1 for the duration of the if block, guaranteeing the object cannot be destroyed while in use.
  • If the target object has already been destroyed (use_count == 0): wp.lock() returns an empty std::shared_ptr<T> (nullptr), which evaluates to false in the if condition.
auto orig = std::make_shared<int>(42); // use_count == 1
std::weak_ptr<int> wp(orig);           // Observes without incrementing count (use_count == 1)

if (auto sp = wp.lock()) {
    // 1. Target is alive: returns valid shared_ptr 'sp' and increments [use_count == 2] inside this block!
    // 2. Dereference (*, ->) using the returned shared_ptr 'sp'
    *sp = 100;
} // 3. Leaving the if block destroys 'sp', decrementing [use_count == 1]

orig.reset(); // Releases ownership -> [use_count == 0], int object is destroyed!
if (auto sp = wp.lock()) {
    // Target is already destroyed: wp.lock() returns empty shared_ptr (nullptr), skipping this block
}