C++ shared_ptr vs unique_ptr: Smart Pointer Choice Guide

C++ shared_ptr vs unique_ptr: Smart Pointer Choice Guide

이 글의 핵심

Practical guide to shared_ptr vs unique_ptr: ownership, overhead, weak_ptr, and when to use each.

When you suspect leaks or double-free issues, pair this with practical tooling in memory leak detection.

Introduction: “shared_ptr or unique_ptr?"

"I switched everything to shared_ptr because leaks scare me”

Since C++11, smart pointers help prevent memory leaks, but picking shared_ptr vs unique_ptr matters for clarity and performance.

std::unique_ptr<int> u = std::make_unique<int>(42);

std::shared_ptr<int> s = std::make_shared<int>(42);
auto s2 = s;  // refcount++

This article covers:

  • Differences
  • Ownership models
  • Overhead
  • Cycles and weak_ptr
  • Selection guide

Table of contents

  1. Ownership
  2. Overhead
  3. Usage
  4. Cycles
  5. Selection
  6. Summary

1. Ownership models

unique_ptr: exclusive ownership

  • Only one owner; move-only
  • Clear ownership transfer

shared_ptr: shared ownership

  • Multiple owners; reference counted
  • Last owner destroys the object

Diagram

flowchart TB
    subgraph unique_ptr
        U1[unique_ptr] --> Obj1[Object]
    end

    subgraph shared_ptr
        S1[shared_ptr] --> Obj2[Object]
        S2[shared_ptr] --> Obj2
        S3[shared_ptr] --> Obj2
        Obj2 -.->|"ref count = 3"| RC[Control block]
    end

2. Overhead

  • unique_ptr: usually pointer-sized
  • shared_ptr: two pointers to object + control block; refcount updates use atomics

Allocation: prefer make_shared / make_unique for exception safety and fewer allocations where applicable.

Typical micro-benchmark pattern: make_unique loops can be slightly faster than make_shared due to control block work—measure your case.


3. Usage

  • unique_ptr: move into sinks; pass .get() for non-owning borrow
  • shared_ptr: copy to extend lifetime for shared consumers

Custom deleters: unique_ptr encodes deleter in the type; shared_ptr erases deleter type.


4. Cycles and weak_ptr

Doubly-linked nodes with shared_ptr both directions can leak—use weak_ptr on the back edge.


5. Selection guide

SituationPrefer
Defaultunique_ptr
True shared ownershipshared_ptr
Factory returns ownershipunique_ptr
Observers / cachesoften weak_ptr

Summary

  1. Default: unique_ptr
  2. Share only when needed: shared_ptr
  3. Break cycles: weak_ptr
  4. Use make_unique / make_shared

  • C++ smart pointers
  • RAII
  • Memory leaks
  • Move semantics

Keywords

shared_ptr vs unique_ptr, smart pointers, ownership, weak_ptr, RAII


... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3