1. 어디다 쓰나?
shared_ptr for shared ownership, unique_ptr for ownership transfer
2. custom deleter 지정하기
2.1 shared_ptr의 경우 해당 포인터를 인자로 받는 functor를 constructor의 2번째 인자로 넘겨 준다.
std::shared_ptr<int> sp(new int[10], [](int * p) { delete [] p; });
2.2 unique_ptr의 경우 custom deleter의 타입을 2번째 template argument로 넘겨줘야 한다.
int * GetResource(); auto lam = [](int * p) { // do something... Release(p); }; std::unique_ptr<int, decltype(lam)> up1(GetResource(), lam); // other example std::unique_ptr<int, void (*)(int *)> up2(new int[10], [](int * p) { delete [] p; }); // other example std::unique_ptr<int, std::function<void (int *)>> up3(new int[20],
[](int * p) { delete [] p; });
3. array를 다룰 때
#include <memory> // shared_ptr의 경우 custom deleter로 지정해야 함. std::shared_ptr<int> sp(new int[10], [](int * p) { delete [] p; }); // unique_ptr의 경우 array를 위한 specialization이 있음. std::unique_ptr<int[]> up(new int[10]);
'programming > C++' 카테고리의 다른 글
C++11 cheat sheet (0) | 2013.02.18 |
---|---|
Universal reference (0) | 2013.02.18 |
std::async and std::future 쓸 때... (0) | 2013.02.18 |
constexpr (0) | 2013.02.18 |
Uniform initialization in C++11 (0) | 2013.02.18 |