C++11부터 생긴 `std::unique_ptr`과 기존에 `std::auto_ptr`의 차이를 알고싶습니다. 둘이 사용법은 비슷한것 같던데 정확이 무슨 차이가 있는가요?
조회수 1677회
1 답변
-
대부분의 경우 둘은 동일한 일을 합니다. 다만 다른점은
auto_ptr
은 복사(copy)가 가능한 반면,unique_ptr
은 이동(move)만 가능합니다.무슨말인가 하면,
auto_ptr
은std::auto_ptr<int> p(new int); std::auto_ptr<int> p2 = p;
가 가능하지만,
unique_ptr
은 이게 불가능 합니다.unique_ptr
로 위 코드를 흉내내려면std::unique_ptr<int> p(new int); std::unique_ptr<int> p2 = std::move(p);
같이 써야 하지요.
다른 차이로는
unique_ptr
이 배열을 좀 더 잘 다룬다는 점입니다.auto_ptr
에서는delete
를 call하지만unique_ptr
은delete[]
를 call합니다.
댓글 입력