C++中智能指標(smarter pointer)自訂刪除器(deleter) 的方法

來源:互聯網
上載者:User

智能指標包含兩種"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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.