티스토리 뷰
많은 사람들이 배우면서 어렵다고 느끼는 pointer를 쉽게 관리하기 위해 사용하는 스마트 포인터에 대해 알아보겠습니다.
c++에는 unique_ptr, shared_ptr, weak_ptr 이 제공되고 있습니다.
unique_ptr은 인스턴스의 소유권을 유일하게 가지는 스마트 포인터이고
shared_ptr은 인스턴스의 소유권을 공유하는 스마트 포인터이고
weak_ptr은 인스턴스의 소유권을 가지지 않는 스마트 포인터이다.
헤더 추가 :
#include <memory>
일단 unique_ptr부터 살펴보면 (1)과 같이 사용하여 해당 인스턴스의 소유권을 유일하게 가지게 되는데 만약 해당 인스턴스의 소유권을 또 가지는 스마트 포인터가 생기면 할당된 메모리를 중복해제하여 에러가 발생하게 된다.
std::unique_ptr<int> uniquePtr(new int(1));
그렇기 때문에 unique_ptr은 스마트 포인터끼리의 인스턴스 복사는 안되며 std::move를 이용하여 이동은 가능합니다.
shared_ptr은 인스턴스의 소유권을 여러 스마트 포인터가 공유할 수 있습니다. 다음과 같이 소유권을 공유해보고 카운트를 확인해보면 공유한만큼 늘어난 것을 확인 할 수 있습니다.
std::shared_ptr<int> sharedPtr1(new int(1));
std::shared_ptr<int> sharedPtr2(sharedPtr1);
std::shared_ptr<int> sharedPtr3(sharedPtr2);
std::cout << sharedPtr1.use_count() << std::endl;
마지막으로 weak_ptr은 해당 인스턴스의 소유권을 가지지 않습니다. 이 말은, shared_ptr과 다르게 참조 카운팅에는 들어가지 않기 때문에 weak_ptr이 인스턴스를 참조하고 있어도 메모리 해제가 된다는 얘기입니다. 또한, weak_ptr은 unique_ptr이나 shared_ptr과 다르게 lock()을 통해서 참조된 shared_ptr을 반환받은 후 사용할 수 있습니다.
std::shared_ptr<int> sharedPtr(new int(1));
std::weak_ptr<int> weakPtr(sharedPtr);
if (auto spt = weakPtr.lock())
{
std::cout << *weakPtr << "\n" << std::endl;
}
else
{
std::cout << "weakPtr is expired\n" << std::endl;
}
코드 작성에 대한 얘기를 마지막으로 하자면 위의 int같이 기본 타입에 대한 작성은 짧고 간단하게 쓸 수 있지만 class같은 타입에 대해서는 (1)과 같이 길어집니다. 이 문장을 auto와 make_shared를 이용하여 짧게 작성하면 (2)와 같습니다.
(1) std::shared_ptr<TestClass> sharedPtr = std::shared_ptr<TestClass>(new TestClass());
(2) auto sharedPtr = std::make_shared<TestClass>();
스마트 포인터가 모든것을 해결해 주지는 않지만 이렇게 new로 할당하고 나면 delete로 하나하나 해제하던 때와는 다르게 쉽게 사용할 수 있는 것을 확인 할 수 있습니다.
'c++' 카테고리의 다른 글
[c++ 11] auto (0) | 2017.02.08 |
---|
- Total
- Today
- Yesterday
- android open source
- type inference
- publish opensource
- android serialization
- data transfer
- serializable
- RecyclerView
- delete item
- git server
- auto depoly
- expandable recyclerview
- Apache
- Parcelable
- C++
- 자동 배포
- Jenkins
- weak_ptr
- jitpack
- build server
- git hook
- qtwebengine
- security.ubuntu.com
- 오픈 소스 배포
- swip
- Git
- remove item
- kotlinx serialization
- kotlin
- ubuntu 16.04
- 리사이클러뷰 확장
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |