您的位置:首页 > 编程语言 > C语言/C++

C++ - 智能指针(smarter pointer)自定义删除器(deleter) 的方法 详解 及 代码

2013-11-25 09:02 459 查看

智能指针(smarter pointer)自定义删除器(deleter) 的方法 详解 及 代码

 
版权所有, 禁止转载, 如有需要, 请站内联系
本文地址: 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息