c++模板偏特化的應用

來源:互聯網
上載者:User
動機

考慮這樣一個需求, 在某項目中需要對動態記憶體進行限制以避免產生記憶體片段這樣的問題,需要實現一個記憶體池。讓項目中的一些對象在記憶體池中拿取資料而不是直接用new在堆中取資料。那麼對於一個對象的產生我們需要把記憶體配置和構造分開,同樣的析構和記憶體收回也需要分開。對於前者,我們可以使用placement new來完成。後者則顯式的調用解構函式。

講到這裡就有一個問題,自訂的結構體和類是有解構函式的,但是原始類型(int,double)是沒有解構函式的,怎麼辦呢。 實現

先不考慮過多,把基本的寫出來

//構造對象template<class T1>inline void construct(T1 *p){    new (p)T1();//placement new}//清除對象template<classs T>void destory(T &e){    e.~T();}

為了區分T是否有建構函式,用兩個標誌類型進行區分

//清除類型struct _false_type{};struct _true_type{};//有解構函式則繼承這個結構體struct destoryType{    typedef _true_type has_destory;};//清除類型萃取器template<class T>struct _type_traits{    typedef typename T::has_destory has_destory;};//利用特化版本,針對基本類型定義has_destory為_false_typetemplate<class T>struct _type_traits<T*>{    typedef  _false_type has_destory;};//新版本 destory template<class T>void destory(T &ele){     _destory(ele, _type_traits<T>::has_destory());}template<class T>void _destory(T &ele, _true_type){    ele.~T();}template<class T>void _destory(T &ele, _false_type){}
測試代碼

在棧上上面取記憶體,在擷取的記憶體上構造對象並銷毀。不釋放記憶體

int main(){    char buff1[8];    char buff2[8];    int * p1 = reinterpret_cast<int*>(buff1);    Img * p2 = reinterpret_cast<Img*>(buff2);    construct<int>(p1);    construct<Img>(p2);    destory<int*>(p1);//普通類型    destory<Img>(*p2);//自訂類型    getchar();    return 0;}//output://construct Img//destory Img
參考:

《STL源碼剖析》中空間配置器的部分實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.