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 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
| Situation | Prefer |
|---|---|
| Default | unique_ptr |
| True shared ownership | shared_ptr |
| Factory returns ownership | unique_ptr |
| Observers / caches | often weak_ptr |
Summary
- Default:
unique_ptr - Share only when needed:
shared_ptr - Break cycles:
weak_ptr - Use make_unique / make_shared
Related reading
- C++ smart pointers
- RAII
- Memory leaks
- Move semantics
Keywords
shared_ptr vs unique_ptr, smart pointers, ownership, weak_ptr, RAII
Related posts
- Browse the C++ series
- malloc vs new vs make_unique
- Circular reference