STL記憶體空間的配置/釋放與對象內容的構造/析構,是分開進行的。 對象的構造、析構 對象的構造由construct函數完成,該函數內部調用定位new運算符,在指定的記憶體位置構造對象。如下: template <typename T1, typename T2> inline void constru ...
STL記憶體空間的配置/釋放與對象內容的構造/析構,是分開進行的。
對象的構造、析構
對象的構造由construct函數完成,該函數內部調用定位new運算符,在指定的記憶體位置構造對象。如下:![](file:///D:/%E6%88%91%E7%9A%84%E6%96%87%E6%A1%A3/My%20Knowledge/temp/720808c1-4dbb-4acc-8dcf-3c3b4d3fb8dd/128/index_files/f9f4441b-8c6e-40b6-ac78-c1ddf984f9c4.png)
template <typename T1, typename T2> inline void construct(T1 *p, const T2& value) { //定位new new (p) T1(value); }
對象的析構由destroy函數完成,該函數有兩個版本:接受1個指針和接收兩個迭代器的版本。接受1個指針的版本直接調用指針指向的對象的析構函數完成析構;接收兩個迭代器的版本的destroy會判斷迭代器指向的對象類型的析構函數是否是trivial的,若是,則什麼也不做,若不是,則會遍歷兩個迭代器所指定的範圍,逐個調用第1版本的destroy。這麼做的目的主要是為了析構時的效率考慮。 下圖為第1版本的destroy
//destroy()第一版本,接受一個指針 template <typename T> inline void destroy(T* point) { point->~T(); }
![](file:///D:/%E6%88%91%E7%9A%84%E6%96%87%E6%A1%A3/My%20Knowledge/temp/720808c1-4dbb-4acc-8dcf-3c3b4d3fb8dd/128/index_files/1f5cfa1e-a22f-40e8-b33f-5f8827d93d21.png)
//有trivial destructor template <typename Iterator> inline void __destroy_aux(Iterator first, Iterator last, __true_type) {} //有non-trivial destructor template <typename Iterator> inline void __destroy_aux(Iterator first, Iterator last, __false_type) { for (; first < last; first++) destroy(&*first); //調用第一版本destroy() } //判斷元素的值類型是否有trivial destructor template <typename Iterator, typename T> inline void __destroy(Iterator first, Iterator last, T* ) { typedef typename __type_traits<T>::has_trivial_destructor trivial_destructor; __destroy_aux(first, last, trivial_destructor()); } //destroy()第二版本,接受兩個迭代器 template <typename Iterator> inline void destroy(Iterator first, Iterator last) { __destroy(first, last, value_type(first)); }
其中,判斷迭代器所指的對象類型,是通過iterator_traits模板結構體來判斷的,利用了模板的參數推斷功能,從而推斷出該迭代器所指的對象類型。如下圖所示:
![](file:///D:/%E6%88%91%E7%9A%84%E6%96%87%E6%A1%A3/My%20Knowledge/temp/720808c1-4dbb-4acc-8dcf-3c3b4d3fb8dd/128/index_files/b3c2d248-f524-4a30-af33-f5f2df7b3a5a.png)
//返回迭代器指向的對象類型 value_type* template <typename Iterator> inline typename iterator_traits<Iterator>::value_type* value_type(const Iterator&) { return static_cast<typename iterator_traits<Iterator>::value_type*>(NULL); }
//iterator traits template <typename Iterator> struct iterator_traits { typedef typename Iterator::iterator_category iterator_category; typedef typename Iterator::value_type value_type; typedef typename Iterator::difference_type difference_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; };
![](file:///D:/%E6%88%91%E7%9A%84%E6%96%87%E6%A1%A3/My%20Knowledge/temp/720808c1-4dbb-4acc-8dcf-3c3b4d3fb8dd/128/index_files/0f75a9c9-137f-40b9-b41a-c42485d0ba6c.png)
(全文完)
附: STL系列文章:http://www.cnblogs.com/zxiner/p/7197402.html 一款簡易版STL的實現,項目地址:https://github.com/zinx2016/MiniSTL/tree/master/MiniSTL