動機
考慮這樣一個需求, 在某項目中需要對動態記憶體進行限制以避免產生記憶體片段這樣的問題,需要實現一個記憶體池。讓項目中的一些對象在記憶體池中拿取資料而不是直接用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源碼剖析》中空間配置器的部分實現