unique_ptr — std::unique_ptr
unique_ptr — std::unique_ptr
std::unique_ptr는 **독점 소유권(unique ownership)**을 가진 스마트 포인터예요. 한 객체를 오직 하나의 unique_ptr만 소유할 수 있어요.
동적 메모리를 소유하되, 복사 불가·이동 가능으로 수명을 자동 관리해요. unique_ptr가 파괴되면 가리키던 객체가 삭제돼요. std::auto_ptr의 안전한 대체품이에요.
출처: cppreference
본문
std::unique_ptr는 독점 소유권 스마트 포인터예요.
template<class T, class Deleter = std::default_delete<T>>
class unique_ptr;
특정 객체를 유일하게 소유해요. 파괴되면 소유한 객체를 삭제해요. 복사할 수 없고 이동만 가능해요.
기본 사용
auto p = std::make_unique<int>(42); // 권장 생성
std::unique_ptr<int> p2 = std::make_unique<int>(7);
// p2 = p; // 오류: 복사 불가
p2 = std::move(p); // 이동: 소유권 이전 (p 는 nullptr)
int n = *p2; // 역참조
특징
- 독점 소유권 — 한 객체 하나의 소유자
- 복사 불가, 이동 가능 — 소유권 이전은 이동으로
- 자동 해제 — 파괴 시
delete - 배열 지원 —
std::unique_ptr<T[]>
생성
auto p = std::make_unique<std::string>("hello"); // 단일 객체
auto arr = std::make_unique<int[]>(10); // 배열
make_unique가 안전하고 효율적이에요.
커스텀 삭제자
두 번째 템플릿 인자로 삭제자를 지정할 수 있어요.
auto file = std::unique_ptr<FILE, decltype(&std::fclose)>(
std::fopen("f.txt", "r"), &std::fclose);
이동과 소유권
함수 반환이나 std::move로 소유권을 이전해요. 이동 후 원본은 nullptr이 돼요.
std::unique_ptr<Widget> make_widget() {
return std::make_unique<Widget>();
}
auto w = make_widget(); // 반환에서 이동
컨테이너와의 사용
unique_ptr는 이동 가능하므로 std::vector에 넣을 수 있어요 (복사 불가지만 이동은 가능).
std::vector<std::unique_ptr<int>> v;
v.push_back(std::make_unique<int>(1));
노트 (Notes)
unique_ptr는 예외 안전하고 자원 누수가 없어요 (RAII).- 복사가 필요하면
shared_ptr를 써요. get()은 원시 포인터,release()는 소유권 포기 후 반환,reset()은 교체.