C++ RAII & Smart Pointers | "스마트 포인터" 가이드
이 글의 핵심
C++ RAII & Smart Pointers에 대한 실전 가이드입니다.
RAII와 스마트 포인터란?
RAII (Resource Acquisition Is Initialization) 는 자원 획득은 초기화라는 C++ 핵심 원칙으로, 객체 생성 시 자원을 획득하고 소멸 시 자동 해제합니다. 스마트 포인터는 RAII를 구현한 대표적인 예입니다.
// ❌ 수동 관리
int* ptr = new int(10);
// ... 예외 발생 시 누수
delete ptr;
// ✅ 스마트 포인터
auto ptr = std::make_unique<int>(10);
// 자동 소멸
왜 필요한가?:
- 자동 해제: 소멸자에서 자동 정리
- 예외 안전: 예외 발생 시에도 안전
- 메모리 누수 방지: delete 누락 방지
- 소유권 명확: 누가 자원을 소유하는지 명확
// ❌ 수동 관리: 예외 시 누수
void func() {
int* ptr = new int(10);
if (error) {
throw std::runtime_error("에러"); // 누수!
}
delete ptr;
}
// ✅ RAII: 예외 안전
void func() {
auto ptr = std::make_unique<int>(10);
if (error) {
throw std::runtime_error("에러"); // 자동 해제
}
}
RAII 동작 원리:
flowchart LR
A[객체 생성] --> B[자원 획득]
B --> C[사용]
C --> D[예외 발생?]
D -->|Yes| E[스택 되감기]
D -->|No| F[정상 종료]
E --> G[소멸자 호출]
F --> G
G --> H[자원 해제]
스마트 포인터 종류:
| 타입 | 소유권 | 복사 | 이동 | 사용 시나리오 |
|---|---|---|---|---|
unique_ptr | 독점 | ❌ | ✅ | 단일 소유자 |
shared_ptr | 공유 | ✅ | ✅ | 여러 소유자 |
weak_ptr | 없음 | ✅ | ✅ | 순환 참조 방지 |
// unique_ptr: 독점 소유권
std::unique_ptr<int> u = std::make_unique<int>(10);
// auto u2 = u; // 에러: 복사 불가
auto u2 = std::move(u); // OK: 이동
// shared_ptr: 공유 소유권
std::shared_ptr<int> s = std::make_shared<int>(10);
auto s2 = s; // OK: 복사 (참조 카운트 증가)
// weak_ptr: 관찰만
std::weak_ptr<int> w = s;
if (auto ptr = w.lock()) { // 사용 시 lock
std::cout << *ptr << '\n';
}
unique_ptr
#include <memory>
// 독점 소유권
std::unique_ptr<int> ptr = std::make_unique<int>(10);
// 이동만 가능
auto ptr2 = std::move(ptr); // ptr은 nullptr
shared_ptr
// 공유 소유권
std::shared_ptr<int> ptr1 = std::make_shared<int>(10);
std::shared_ptr<int> ptr2 = ptr1; // 참조 카운트 증가
// 마지막 shared_ptr 소멸 시 자원 해제
실전 예시
예시 1: unique_ptr 기본
class Resource {
public:
Resource() { std::cout << "생성" << std::endl; }
~Resource() { std::cout << "소멸" << std::endl; }
void use() { std::cout << "사용" << std::endl; }
};
void func() {
auto ptr = std::make_unique<Resource>();
ptr->use();
// 함수 종료 시 자동 소멸
}
int main() {
func();
// "생성" -> "사용" -> "소멸"
}
예시 2: shared_ptr 참조 카운트
void func() {
auto ptr1 = std::make_shared<int>(10);
std::cout << "카운트: " << ptr1.use_count() << std::endl; // 1
{
auto ptr2 = ptr1;
std::cout << "카운트: " << ptr1.use_count() << std::endl; // 2
}
std::cout << "카운트: " << ptr1.use_count() << std::endl; // 1
}
예시 3: 컨테이너
std::vector<std::unique_ptr<Widget>> widgets;
widgets.push_back(std::make_unique<Widget>(1));
widgets.push_back(std::make_unique<Widget>(2));
// 벡터 소멸 시 모든 Widget 자동 소멸
예시 4: 팩토리 패턴
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Circle" << std::endl;
}
};
std::unique_ptr<Shape> createShape(const std::string& type) {
if (type == "circle") {
return std::make_unique<Circle>();
}
return nullptr;
}
weak_ptr
auto shared = std::make_shared<int>(10);
std::weak_ptr<int> weak = shared;
// 사용 시 lock
if (auto ptr = weak.lock()) {
std::cout << *ptr << std::endl;
}
자주 발생하는 문제
문제 1: 순환 참조
// ❌ 순환 참조
class Node {
public:
std::shared_ptr<Node> next;
std::shared_ptr<Node> prev; // 순환 참조
};
// ✅ weak_ptr 사용
class Node {
public:
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // 순환 방지
};
문제 2: this 포인터
// ❌ this를 shared_ptr로
class Bad {
public:
std::shared_ptr<Bad> getPtr() {
return std::shared_ptr<Bad>(this); // 위험!
}
};
// ✅ enable_shared_from_this
class Good : public std::enable_shared_from_this<Good> {
public:
std::shared_ptr<Good> getPtr() {
return shared_from_this();
}
};
문제 3: 배열
// ❌ 배열 삭제 문제
std::unique_ptr<int> ptr(new int[10]); // delete 호출
// ✅ 배열 특수화
std::unique_ptr<int[]> ptr(new int[10]); // delete[] 호출
// ✅ make_unique (C++14)
auto ptr = std::make_unique<int[]>(10);
문제 4: 커스텀 삭제자
// FILE* 관리
auto deleter = {
if (f) fclose(f);
};
std::unique_ptr<FILE, decltype(deleter)> file(
fopen("file.txt", "r"), deleter
);
성능 비교
// unique_ptr: 포인터 크기
sizeof(std::unique_ptr<int>); // 8바이트
// shared_ptr: 포인터 + 제어 블록
sizeof(std::shared_ptr<int>); // 16바이트
실무 패턴
패턴 1: 팩토리 함수
class Connection {
public:
Connection(const std::string& host) : host_(host) {
std::cout << "연결: " << host_ << '\n';
}
~Connection() {
std::cout << "연결 종료: " << host_ << '\n';
}
void query(const std::string& sql) {
std::cout << "쿼리: " << sql << '\n';
}
private:
std::string host_;
};
std::unique_ptr<Connection> createConnection(const std::string& host) {
return std::make_unique<Connection>(host);
}
// 사용
auto conn = createConnection("localhost");
conn->query("SELECT * FROM users");
// 자동 연결 종료
패턴 2: 캐시 시스템
#include <map>
#include <memory>
#include <string>
class Cache {
std::map<std::string, std::weak_ptr<Resource>> cache_;
public:
std::shared_ptr<Resource> get(const std::string& key) {
// 캐시 확인
if (auto it = cache_.find(key); it != cache_.end()) {
if (auto ptr = it->second.lock()) {
return ptr; // 캐시 히트
}
}
// 캐시 미스: 새로 생성
auto resource = std::make_shared<Resource>(key);
cache_[key] = resource;
return resource;
}
};
패턴 3: 소유권 전달
class TaskQueue {
std::vector<std::unique_ptr<Task>> tasks_;
public:
void addTask(std::unique_ptr<Task> task) {
tasks_.push_back(std::move(task));
}
std::unique_ptr<Task> getNextTask() {
if (tasks_.empty()) {
return nullptr;
}
auto task = std::move(tasks_.back());
tasks_.pop_back();
return task;
}
};
// 사용
TaskQueue queue;
queue.addTask(std::make_unique<Task>("Task1"));
auto task = queue.getNextTask(); // 소유권 이동
task->execute();
FAQ
Q1: 언제 사용하나요?
A:
unique_ptr: 독점 소유권, 단일 소유자shared_ptr: 공유 소유권, 여러 소유자weak_ptr: 순환 참조 방지, 관찰만
// unique_ptr: 독점
std::unique_ptr<Widget> widget = std::make_unique<Widget>();
// shared_ptr: 공유
std::shared_ptr<Widget> shared = std::make_shared<Widget>();
auto shared2 = shared; // 복사
// weak_ptr: 관찰
std::weak_ptr<Widget> weak = shared;
Q2: 성능은?
A:
unique_ptr: raw pointer와 동일 (오버헤드 없음)shared_ptr: 참조 카운트 오버헤드 (원자적 연산)
// unique_ptr: 8바이트
sizeof(std::unique_ptr<int>); // 8
// shared_ptr: 16바이트 (포인터 + 제어 블록)
sizeof(std::shared_ptr<int>); // 16
Q3: 배열은 어떻게 사용하나요?
A: unique_ptr<T[]> 를 사용합니다.
// ❌ 배열 삭제 문제
std::unique_ptr<int> ptr(new int[10]); // delete 호출 (잘못됨)
// ✅ 배열 특수화
std::unique_ptr<int[]> ptr(new int[10]); // delete[] 호출
// ✅ make_unique (C++14)
auto ptr = std::make_unique<int[]>(10);
Q4: 순환 참조는 어떻게 해결하나요?
A: weak_ptr 로 해결합니다.
// ❌ 순환 참조
class Node {
std::shared_ptr<Node> next;
std::shared_ptr<Node> prev; // 순환 참조
};
// ✅ weak_ptr
class Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // 순환 방지
};
Q5: 언제 raw pointer를 사용하나요?
A:
- 소유권 없음: 관찰만
- 함수 매개변수: 임시 참조
- 성능 중요: 핫 패스
// raw pointer: 소유권 없음
void process(Widget* widget) {
widget->use(); // 관찰만
}
// unique_ptr: 소유권 있음
std::unique_ptr<Widget> owner = std::make_unique<Widget>();
process(owner.get()); // raw pointer 전달
Q6: make_unique vs new?
A: make_unique를 권장합니다.
// ❌ new: 예외 안전하지 않음
func(std::unique_ptr<Widget>(new Widget()), compute());
// compute()에서 예외 발생 시 누수 가능
// ✅ make_unique: 예외 안전
func(std::make_unique<Widget>(), compute());
Q7: 커스텀 삭제자는?
A: 람다나 함수 객체를 사용합니다.
// FILE* 관리
auto deleter = {
if (f) fclose(f);
};
std::unique_ptr<FILE, decltype(deleter)> file(
fopen("file.txt", "r"), deleter
);
Q8: 스마트 포인터 학습 리소스는?
A:
- “Effective Modern C++” by Scott Meyers (Item 18-22)
- “C++ Primer” by Stanley Lippman
- cppreference.com - Smart pointers
관련 글: unique_ptr, shared_ptr, weak_ptr.
한 줄 요약: RAII와 스마트 포인터는 자동 자원 관리로 메모리 누수를 방지하는 C++ 핵심 기법입니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ 스마트 포인터 | unique_ptr/shared_ptr “메모리 안전” 가이드
- C++ 스마트 포인터 | 3일 동안 찾지 못한 순환 참조 버그 해결법
- C++ 스마트 포인터 기초 완벽 가이드 | unique_ptr·shared_ptr
관련 글
- C++ shared_ptr vs unique_ptr |
- C++ 스마트 포인터 | 3일 동안 찾지 못한 순환 참조 버그 해결법
- C++ 스마트 포인터 기초 완벽 가이드 | unique_ptr·shared_ptr
- C++ RAII 완벽 가이드 |
- C++ 스마트 포인터 | unique_ptr/shared_ptr