Post

Smart Pointers

Smart Pointers

Smart Pointers


Prerequisites


1. What is a Smart Pointers

A smart pointer is a wrapper around a raw pointer that automatically manages memory.

It prevents:

  • memory leaks
  • double free
  • dangling pointers
1
2
Raw Pointer → manual delete
Smart Pointer → Automatically management (RAII)

Smart pointers are based on RAII (Resource Acquisition Is Initialization)

  • resource acquired in constructor
  • released in destructor

2. Why Use Smart Pointers

❌ Raw Pointer Problem

1
2
int* p = new int(10);
// forgot delete → memory leak

✔️ Smart Pointer Solution

1
2
std::unique_ptr<int> p = std::make_unique<int>(10);
// 자동으로 delete됨

3. Types of Smart Pointers

3-1. std::unique_ptr

  • exclusive ownership
  • copy impossible
  • move possible
Example
1
2
3
#include <memory>

auto p = std::make_unique<int>(10);
✔️ Move
1
2
auto p1 = std::make_unique<int>(10);
auto p2 = std::move(p1);

3-2. std::shared_ptr

  • shared ownership
  • reference counting
Example
1
2
3
4
#include <memory>

auto p1 = std::make_shared<int>(10);
auto p2 = p1;  // 공유
✔️ Reference Count
1
p1.use_count();  // how many shared pointer shared

Internal architecture

1
2
3
4
Control Block:
- reference count
- weak count
- pointer

3-3. std::weak_ptr

  • References a shared_ptr without owning it
  • Does not increase the reference count
Example
1
2
std::shared_ptr<int> sp = std::make_shared<int>(10);
std::weak_ptr<int> wp = sp;
✔️ Access
1
2
if (auto s = wp.lock())
    std::cout << *s;

prevent circular reference

Circular Reference Problem
1
2
3
4
5
6
7
8
9
10
11
12
struct A;
struct B;

struct A
{
    std::shared_ptr<B> b;
};

struct B
{
    std::shared_ptr<A> a;
};
1
2
3
4
5
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();

a->b = b;
b->a = a;
1
2
A: count = 2 (a, b->a)
B: count = 2 (b, a->b)

They hold references to each other → memory is never released

1
2
a.reset();
b.reset();
1
2
A: count = 1 (B hold A)
B: count = 1 (A hold B)
✔️ Resolution
1
2
3
4
struct B
{
    std::weak_ptr<A> a;
};

4. Performance Comparison

unique_ptr / shared_ptr / weak_ptr

TypeSpeedOverhead
unique_ptr🔥 fastestNone
shared_ptr⚡ mediumreference count
weak_ptr⚡ lowcontrol block

Smart Pointer vs Raw Pointer

FeatureRaw PointerSmart Pointer
Memory safety
Ownership tracking
Performance🔥 fastestslightly slower
Ease of use

5. Miscellaneous

Custom Deleter

1
2
std::unique_ptr<FILE, decltype(&fclose)>
    file(fopen("test.txt", "r"), &fclose);

possible to resource management

This post is licensed under CC BY 4.0 by the author.