当前位置:天才代写 > tutorial > C语言/C++ 教程 > C++中智能指针(smarter pointer)自界说删除器(deleter) 的要领

C++中智能指针(smarter pointer)自界说删除器(deleter) 的要领

2017-11-02 08:00 星期四 所属: C语言/C++ 教程 浏览:1034

智能指针包括两种"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

作者:csdn博客 Spike_King

 

    关键字:

天才代写-代写联系方式