C++

(C++11) shared_ptr, enable_shared_from_this

Awesome Red Tomato 2022. 4. 28. 16:37

shared_ptr

https://docs.microsoft.com/ko-kr/cpp/standard-library/shared-ptr-class?view=msvc-170 

 

shared_ptr 클래스

자세한 정보: shared_ptr 클래스

docs.microsoft.com

 

shared_ptr은 포인터를 통해 개체의 공유 소유권을 유지하는 smart pointer이다. 여러 개체가 동일한 개체를 소유하면 reference counter(참조 카운터)를 1증가하고, 해제하면 1감소시킨다. 참조 카운터가 0이 되면 할당을 해제한다.

 

 

 

 

 

enable_shared_from_this

https://docs.microsoft.com/ko-kr/cpp/standard-library/enable-shared-from-this-class?view=msvc-170 

 

enable_shared_from_this 클래스

자세한 정보: enable_shared_from_this 클래스

docs.microsoft.com

 

만약 두 shared_ptr 객체가 같은 객체를 갖는다고 해보자.

Tomato* tomato = new Tomato;

std::shared_ptr<Tomato> t1(tomato);
std::shared_ptr<Tomato> t2(tomato);	// error

 

t1과 t2는 같은 tomato를 갖는 다른 포인터이기 때문에 런타임 에러가 생긴다. 이를 방지하기 위해 클래스를 구현할 때 자기 자신의 shared_ptr 객체를 알 수 있게 해주는 std::enable_shared_from_this를 상속한다. 

class Tomato : public std::enable_shared_from_this<Tomato>
{
public:
	std::shared_ptr<Tomato> GetPtr() { return shared_from_this(); }
}

 

<memory>헤더 enable_shared_from_this

enable_shared_from_this 객체 안에는 자기 자신의 weak_ptr를 가지고 있어 shared_from_this()를 호출하면 자신의 shared_ptr을 반환한다.