weak_ptr — std::weak_ptr

weak_ptr — std::weak_ptr

std::weak_ptrstd::shared_ptr가 소유한 객체를 소유권 없이 관찰하는 스마트 포인터예요. 참조 횟수를 늘리지 않아요.

순환 참조를 방지하거나, 객체의 수명에 영향 없이 어떤 객체가 아직 살아있는지 확인하고 싶을 때 사용해요. lock()으로 임시 shared_ptr를 얻을 수 있어요.

출처: cppreference

본문

std::weak_ptr는 공유 객체를 관찰하는 비소유 스마트 포인터예요.

template<class T> class weak_ptr;

weak_ptr는 소유권이 없어 참조 횟수를 증가시키지 않아요. shared_ptr나 다른 weak_ptr로부터 생성돼요.

기본 사용

std::shared_ptr<int> sp = std::make_shared<int>(42);
std::weak_ptr<int> wp = sp;

if (auto sp2 = wp.lock()) {   // lock: 유효하면 임시 shared_ptr
    std::cout << *sp2 << '\n';
} else {
    // 객체는 이미 소멸됨
}

주요 멤버

  • lock() — 객체가 살아있으면 shared_ptr를 반환, 아니면 빈 shared_ptr 반환
  • expired() — 객체가 소멸했는지 확인
  • use_count() — 공유 객체의 참조 횟수
  • reset() — 관찰 해제

순환 참조 방지

두 객체가 서로를 shared_ptr로 참조하면 참조 횟수가 0이 되지 않아 메모리 누수가 돼요 (순환 참조). 한쪽을 weak_ptr로 두면 깨져요.

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> parent;   // 순환 방지: 약한 참조
};

shared_ptr와의 관계

  • shared_ptrweak_ptr 생성 가능
  • weak_ptrshared_ptrlock()으로 (객체가 살아있는지 확인 후)

weak_ptr는 소유권이 없으므로, 객체를 유지되게 하지 않아요.

노트 (Notes)

  • weak_ptr만으로는 역참조할 수 없어요. 반드시 lock()으로 shared_ptr를 얻어 사용해요.
  • 객체가 살아있는지의 경쟁 상태(race)에서 lock()은 원자적으로 안전해요.
  • 성능 요구가 높을 때 순환 참조가 없는 경우엔 가볍게만 사용돼요.

더 알아보기 (Learn more)

cppreference