[2026] C++ shared_ptr vs unique_ptr: Smart Pointer Choice Complete Guide
이 글의 핵심
shared_ptr vs unique_ptr: prefer unique_ptr by default; use shared_ptr for shared ownership. Reference counting cost, weak_ptr for cycles, and performance-minded patterns.
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
아래 코드는 mermaid를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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_uniqueloops can be slightly faster thanmake_shareddue 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