본문 바로가기
프로그래밍 언어/C,C++

스마트 포인터

by pagehit 2021. 9. 4.
반응형

스마트 포인터(smart pointer)는 객체를 소요하며, 스마트 포인터의 생명주기는 객체와 같거나 길어야 한다.

 

scoped pointers

stdlib에 있는 포인터가 아니다. boost/smart/scoped_ptr.hpp에 있다.

scoped pointer는 어떤 스코프(scope)에서 다른 스코프로 옮겨질 수 없다.(non-transferable) 그리고 객체를 복사할 수 없으며(exclusive ownership), 다른 스마트 포인터가 스코프 포인터의 동적 객체의 소유권을 가질 수 없다.

boost::scoped_ptr<PointedToType> my_ptr{ new PointedToType };

보통 다아나믹 객체를 new를 이용해 생성한 다음, 위처럼 생성자에게 넘겨 준다.

 

unique pointer

transferable하고, 하나의 다이나믹 객체에 대해 독점적인 소유권을 갖기 때문에 복사할 수 없다. <memory> 헤더에 있다.

#include <memory>
std::unique_ptr<int> my_ptr{ new int { 808 } };
auto my_ptr = make_unique<int>(808); // 위와 같음

 

shared pointer

shared pointer는 transferable하고, 단일 객체에 대한 독점적인 소유권을 갖지 않는다(non-exclusive). 즉, shared pointer를 move할 수 있으며(transferable), 복사할 수 있다(non-exclusive). shared pointer가 unique pointer와 다른 점은 복사를 할 수 있다는 것이다.

#inlcude <memory>
std::shared_ptr<int> my_ptr{ new int { 808 } };
auto my_ptr = std::make_shared<int>(808); // template function

 

weak pointer

객체에 대한 소유권(ownership)을 갖지 않는다. weak pointer는 객체를 추적하며, 추적한 객체가 존재하는 경우 shared pointer로 변환할 수 있으며 이때 임시로 소유권을 갖는다. shared pointer와 마찬가지로 movable, copyable이다.

보통 weak pointer는 cache로 사용한다.

반응형

댓글