memory_enable_shared_from_this

memory_enable_shared_from_this (std::enable_shared_from_this)

<memory> 헤더에 정의되어 있어요. 현재 std::shared_ptr로 관리되는 객체가, 그 소유권을 공유하는 추가적인 std::shared_ptr 인스턴스를 안전하게 생성할 수 있게 해주는 기반 클래스예요. C++11부터 도입됐어요.

출처: cppreference

본문

template< class T >
class enable_shared_from_this;

(C++11부터)

std::enable_shared_from_thisstd::shared_ptr pt로 관리 중인 객체 t가, ptt의 소유권을 공유하는 추가 std::shared_ptr 인스턴스 pt1, pt2 등을 안전하게 생성하게 해줘요.

std::enable_shared_from_this<T>를 공개 상속하면 타입 T에 멤버 함수 shared_from_this가 생겨요. T 타입의 객체 tstd::shared_ptr<T> pt로 관리되면, T::shared_from_this 호출은 ptt의 소유권을 공유하는 새 std::shared_ptr<T>를 돌려줘요.

데이터 멤버

  • mutable std::weak_ptr<T> weak_this: *this의 첫 공유 소유자의 제어 블록을 추적하는 객체 (설명 전용 멤버 객체)

멤버 함수

  • (생성자): enable_shared_from_this 객체 생성 (protected 멤버 함수)
  • (소멸자): enable_shared_from_this 객체 파괴 (protected 멤버 함수)
  • operator=: *this에 대한 참조 반환 (protected 멤버 함수)
  • shared_from_this: *this와 소유권을 공유하는 shared_ptr 반환
  • weak_from_this (C++17): *this를 추적하는 weak_ptr 반환

shared_from_this는 임시 shared_ptr이 아닌, 이미 존재하는 shared_ptr 소유권을 공유한다는 점이 중요해요. 객체가 아직 shared_ptr로 관리되지 않는 상태에서 호출하면 std::bad_weak_ptr 예외가 던져져요.

struct Good : std::enable_shared_from_this<Good>
{
    std::shared_ptr<Good> getptr() { return shared_from_this(); }
};

auto gp1 = std::make_shared<Good>();
auto gp2 = gp1->getptr();   // gp1 과 소유권 공유

더 알아보기 (Learn more)

cppreference