下面的介绍的内容定义在:<stl_construct.h>
中。
construct
#include <new.h> //@ 使用 placement new,需要先包含此文件
//@ 将初值 __value 设定到指针所指的空间上
template <class _T1, class _T2>
inline void _Construct(_T1* __p, const _T2& __value) {
new ((void*) __p) _T1(__value); // placement new,调用 _T1::_T1(__value);
}
destroy
destroy 分为两个版本:
- 接受一个指针参数,利用该指针调用析构函数。
- 接受两个迭代器,将指定范围内的对象析构掉。
//@ 第一个版本,接受一个指针,准备将该指针所指之物析构掉。
template <class _Tp>
inline void _Destroy(_Tp* __pointer) {
__pointer->~_Tp();
}
//@ 若是 __false_type,这才以循环的方式遍历整个范围,并在循环中每经历一个对象就调用第一个版本的 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> 判断该类型的析构函数是否需要做什么
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());
}
//@ 调用 __VALUE_TYPE() 获得迭代器所指对象的类别。
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*) {}