C, C++, C#/C++ 공부
[C++11] std::enable_shared_from_this
밥보92
2018. 6. 7. 11:13
반응형
# std::enable_shared_from_this
shared_ptr을 이용하여 동일한 객체에 대한 소유권을 부여하고 싶은 경우
class 혹은 structure를 enable_shared_from_this를 상속받게 한다.
그이유는 shared_ptr을 이용하여 단순히 객체에 대한 소유권을 공유하려고 할 때, 잘못된 참조가 발생할 수 있는데
먼저 객체에 대한 소유권을 보유한 쪽에서 객체를 소멸시켜 버림으로써 나중에 소유권을 공유한 쪽에서 참조 문제가 발생하는 것이다.
enable_shared_from_this의 사용은 이렇게 객체의 생성 및 소멸에 의한 참조 문제를 방지하기 위해 사용이 된다.
class A : public std::enable_shared_from_this<A>
{
....
}
int main ()
{
....
std::shared_ptr<A> ptr1, ptr2;
ptr1 = new A;
ptr2 = ptr1 -> shared_from_this();
}
반응형