智能指標包含兩種"shared_ptr"和"unique_ptr", 由於兩種指標的實現方式不同, 所以傳遞刪除器的方式也不同;
"shared_ptr"的傳遞刪除器(deleter)方式比較簡單, 只需要在參數中添加具體的刪除器函數名, 即可; 注意是單參數函數;
"unique_ptr"的刪除器是函數模板(function template), 所以需要在模板類型傳遞刪除器的類型(即函數指標(function pointer)), 再在參數中添加具體刪除器;
定義函數指標的類型, 包含三種方法(typedef, typedef decltype, using), 也可以直接傳遞decltype;
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
參考注釋, 具體代碼如下:
/* * cppprimer.cpp * * Created on: 2013.11.24 * Author: Caroline */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <memory> using namespace std; void deleter (int* ptr) { delete ptr; ptr = nullptr; std::clog << "shared_ptr delete the pointer." << std::endl; } int main (void) { //定義函數類型 typedef void (*tp) (int*); typedef decltype (deleter)* dp; using up = void (*) (int*); std::shared_ptr<int> spi(new int(10), deleter); std::shared_ptr<int> spi2(new int, deleter); spi2 = std::make_shared<int>(15); std::cout << "*spi = " << *spi << std::endl; std::cout << "*spi2 = " << *spi2 << std::endl; //unique_ptr是模板函數需要刪除器(deleter)類型, 再傳入具體的刪除器 std::unique_ptr<int, decltype(deleter)*> upi(new int(20), deleter); std::unique_ptr<int, tp> upi2(new int(25), deleter); std::unique_ptr<int, dp> upi3(new int(30), deleter); std::unique_ptr<int, up> upi4(new int(35), deleter); std::cout << "*upi = " << *upi << std::endl; std::cout << "*upi2 = " << *upi2 << std::endl; std::cout << "*upi3 = " << *upi3 << std::endl; std::cout << "*upi4 = " << *upi4 << std::endl; return 0; }
輸出:
shared_ptr delete the pointer. shared_ptr delete the pointer. shared_ptr delete the pointer. shared_ptr delete the pointer. shared_ptr delete the pointer. shared_ptr delete the pointer. *spi = 10 *spi2 = 15 *upi = 20 *upi2 = 25 *upi3 = 30 *upi4 = 35
作者:csdn部落格 Spike_King