💡 퀵 접속: cpp.kr/unique_ptr

unique_ptr

C++ 표준 라이브러리의 스마트 포인터로, 동적으로 할당된 객체의 소유권을 관리합니다. 한 번에 하나의 unique_ptr만 객체를 소유할 수 있습니다.

기본 사용법

#include <iostream>
#include <memory>

int main() {
    // 동적 할당
    std::unique_ptr<int> ptr = std::make_unique<int>(42);
    
    // 값 접근
    std::cout << "값: " << *ptr << std::endl;
    
    // 소유권 확인
    if (ptr) {
        std::cout << "포인터가 유효합니다." << std::endl;
    }
    
    // 자동으로 메모리 해제
    return 0;
}

실행 결과:

값: 42
포인터가 유효합니다.

소유권 이전

#include <iostream>
#include <memory>

int main() {
    // 첫 번째 unique_ptr 생성
    std::unique_ptr<int> ptr1 = std::make_unique<int>(100);
    
    // 소유권 이전
    std::unique_ptr<int> ptr2 = std::move(ptr1);
    
    // ptr1은 이제 nullptr
    if (!ptr1) {
        std::cout << "ptr1은 더 이상 소유권이 없습니다." << std::endl;
    }
    
    // ptr2가 값을 소유
    std::cout << "ptr2의 값: " << *ptr2 << std::endl;
    
    return 0;
}

실행 결과:

ptr1은 더 이상 소유권이 없습니다.
ptr2의 값: 100

배열 관리

#include <iostream>
#include <memory>

int main() {
    // 정수 배열 생성
    std::unique_ptr<int[]> arr = std::make_unique<int[]>(5);
    
    // 배열 초기화
    for (int i = 0; i < 5; ++i) {
        arr[i] = i * 10;
    }
    
    // 배열 출력
    std::cout << "배열 요소들: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

배열 요소들: 0 10 20 30 40

참고사항

  • unique_ptr은 memory 헤더에 정의되어 있습니다.
  • make_unique를 사용하여 객체를 생성하는 것이 권장됩니다.
  • 복사가 불가능하며, 소유권은 move를 통해서만 이전할 수 있습니다.
  • 스코프를 벗어나면 자동으로 메모리를 해제합니다.
  • 배열도 관리할 수 있습니다 (unique_ptr<T[]>).
메서드 설명
get() 원시 포인터 반환
reset() 포인터 초기화
release() 소유권 포기
swap() 다른 unique_ptr과 교환
operator* 역참조
operator-> 멤버 접근