前言
construct的源碼注釋
引自https://github.com/steveLauwh/SGI-STL
以及<<STL源碼剖析>>
#ifndef __SGI_STL_INTERNAL_CONSTRUCT_H
#define __SGI_STL_INTERNAL_CONSTRUCT_H
#include <new.h> // placement new
__STL_BEGIN_NAMESPACE
// 將初值 __value 設(shè)定到指針?biāo)傅目臻g上樊展。
template <class _T1, class _T2>
inline void _Construct(_T1* __p, const _T2& __value) {
new ((void*) __p) _T1(__value); // placement new袋励,調(diào)用 _T1::_T1(__value);
}
template <class _T1>
inline void _Construct(_T1* __p) {
new ((void*) __p) _T1();
}
// 第一個(gè)版本网沾,接受一個(gè)指針拟杉,準(zhǔn)備將該指針?biāo)钢镂鰳?gòu)掉呜师。
template <class _Tp>
inline void _Destroy(_Tp* __pointer) {
__pointer->~_Tp();
}
// 若是 __false_type宪郊,這才以循環(huán)的方式遍歷整個(gè)范圍艰匙,并在循環(huán)中每經(jīng)歷一個(gè)對(duì)象就調(diào)用第一個(gè)版本的 destory()。
// 這是 non-trivial destructor
template <class _ForwardIterator>
void
__destroy_aux(_ForwardIterator __first, _ForwardIterator __last, __false_type)
{
for ( ; __first != __last; ++__first)
destroy(&*__first);
}
// 若是 __true_type庇绽,什么都不做锡搜;這是 trivial destructor。
template <class _ForwardIterator>
inline void __destroy_aux(_ForwardIterator, _ForwardIterator, __true_type) {}
// 利用__type_traits<T>判斷該類型的析構(gòu)函數(shù)是否需要做什么瞧掺。
template <class _ForwardIterator, class _Tp>
inline void
__destroy(_ForwardIterator __first, _ForwardIterator __last, _Tp*)
{
typedef typename __type_traits<_Tp>::has_trivial_destructor
_Trivial_destructor;
__destroy_aux(__first, __last, _Trivial_destructor());
}
// 調(diào)用 __VALUE_TYPE() 獲得迭代器所指對(duì)象的類別耕餐。
template <class _ForwardIterator>
inline void _Destroy(_ForwardIterator __first, _ForwardIterator __last) {
__destroy(__first, __last, __VALUE_TYPE(__first));
}
// 第二版本,destroy 泛型特化
inline void _Destroy(char*, char*) {}
inline void _Destroy(int*, int*) {}
inline void _Destroy(long*, long*) {}
inline void _Destroy(float*, float*) {}
inline void _Destroy(double*, double*) {}
#ifdef __STL_HAS_WCHAR_T
inline void _Destroy(wchar_t*, wchar_t*) {}
#endif /* __STL_HAS_WCHAR_T */
// --------------------------------------------------
// Old names from the HP STL.
// construct() 接受一個(gè)指針 __p 和 一個(gè)初值 __value辟狈。
template <class _T1, class _T2>
inline void construct(_T1* __p, const _T2& __value) {
_Construct(__p, __value);
}
template <class _T1>
inline void construct(_T1* __p) {
_Construct(__p);
}
template <class _Tp>
inline void destroy(_Tp* __pointer) {
_Destroy(__pointer);
}
// 第二個(gè)版本肠缔,接受 __first 和 __last 兩個(gè)迭代器,將 [__first, __last)范圍內(nèi)的所有對(duì)象析構(gòu)掉哼转。
template <class _ForwardIterator>
inline void destroy(_ForwardIterator __first, _ForwardIterator __last) {
_Destroy(__first, __last);
}
__STL_END_NAMESPACE
#endif /* __SGI_STL_INTERNAL_CONSTRUCT_H */