끄적이는 메모장

[C++11] std::enable_shared_from_this 본문

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();

}

 

 

반응형

'C, C++, C# > C++ 공부' 카테고리의 다른 글

[C++11] std::all_of, / std::any_of / std::none_of  (0) 2018.06.07
[C++11] std::make_pair / std::move / std::swap  (0) 2018.06.07
[C++11] mutex  (0) 2018.06.01
[C++11] std::bind, std::placeholder  (0) 2018.05.31
[C++11] lambda expression  (0) 2018.05.31