stl_construct.h主要定义了construct和destory函数,construct函数负责对象的构造,destory负责对象的析构。下面是construct函数:
- template <class _T1, class _T2>
- inline void _Construct(_T1* __p, const _T2& __value) {
- new ((void*) __p) _T1(__value);
- }
- template <class _T1>
- inline void _Construct(_T1* __p) {
- new ((void*) __p) _T1();
- }
可以看到都是placement new方式构造对象的。一个是使用的转换构造函数(除非构造函数申明为explicit,当前内置基本类型不在此列,但int a = new int(5)也可以用,但是用的比较少而己),一个是使用的默认函数函数。
剩下的就是destory了,destory关系比较复杂。因为我们是placement new方式构造的对象,所以很多时候调用析构函数并没有什么用。先看看destory部分代码:
- template <class _Tp>
- inline void _Destroy(_Tp* __pointer) {
- __pointer->~_Tp();
- }
- template <class _ForwardIterator>
- void
- __destroy_aux(_ForwardIterator __first, _ForwardIterator __last, __false_type)
- {
- for ( ; __first != __last; ++__first)
- destroy(&*__first);
- }
- template <class _ForwardIterator>
- inline void __destroy_aux(_ForwardIterator, _ForwardIterator, __true_type) {}
- 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());
- }
- template <class _ForwardIterator>
- inline void _Destroy(_ForwardIterator __first, _ForwardIterator __last) {
- __destroy(__first, __last, __VALUE_TYPE(__first));
- }
然后就是特化的基本内置类型了,就是什么都不干。
- 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 */