版权所有, 禁止转载, 如有需要, 请站内联系
本文地址: http://blog.csdn.net/caroline_wendy
智能指针包含两种"shared_ptr"和"unique_ptr", 由于两种指针的实现方式不同, 所以传递删除器的方式也不同;
"shared_ptr"的传递删除器(deleter)方式比较简单, 只需要在参数中添加具体的删除器函数名, 即可; 注意是单参数函数;
"unique_ptr"的删除器是函数模板(function template), 所以需要在模板类型传递删除器的类型(即函数指针(function pointer)), 再在参数中添加具体删除器;
定义函数指针的类型, 包含三种方法(typedef, typedef decltype, using), 也可以直接传递decltype;
参考注释, 具体代码如下:
/* * 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