new操作包含两阶段:1调用::operator new分配内存,2 调用类的构造函数构造对象内容。delete也包含两阶段:1 调用类的析构函数将对象析构,2 调用::operator delete释放内存。STL allocator为了精密分工,将这两阶段操作分开,内存的分配和释放分别由alloc::allocate()和alloc::deallocate()负责,对象的构造和析构分别由::construct和::destroy()负责

1 template <class T1, class T2>
2 inline void construct(T1* p, const T2& value) {
3     new (p) T1(value); //placement new
4 }
5 
6 template <class T>
7 inline void destroy(T* pointer) {
8     pointer->~T();
9 }

destroy()还有第二个版本,接受两个迭代器。其在实现时先找出元素的数值型别,再用__type_traits<>判断是否有trivial destructor:

 1 template <class ForwardIterator>
 2 inline void destroy(ForwardIterator firsrt, ForwardIterator last)  {
 3     __destroy(first, last, value_type(first));
 4 }
 5 
 6 template <class ForwardIterator, class T>
 7 inline void __destroy(ForwardIterator firsrt, ForwardIterator last, T*)  {
 8     typedef typename __type_traits<T>::has_trivial_destructor trivial_destructor;
 9     __destroy_aux(first, last, trivial_destructor());
10 }
11 
12 template <class ForwardIterator>
13 inline void __destroy_aux(ForwardIterator firsrt, ForwardIterator last, __false_type)  {
14     for( ; first < last; ++first)
15         destroy(&*first);
16 }
17 
18 template <class ForwardIterator>
19 inline void __destroy_aux(ForwardIterator firsrt, ForwardIterator last, __true_type)  {   }

这两个(仅)作为构造,析构之用的(不涉及内存的分配与释放)函数设计为全局函数。

 

    基于construct(),有以下三个函数:

1 template <class InputIterator, class ForwardIterator>
2 ForwardIterator  uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator result);
3 
4 template <class ForwardIterator, class T>
5 void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x);
6 
7 template <class ForwardIterator, class Size, class T>
8 ForwardIterator  uninitialized_fill(ForwardIterator first, Size n, const T& x);

上述函数在实现时类似destory的第二个版本,先取value_type,再使用__type_traits<>判断型别是否为POD,如果是,分别调用高阶的copy(),fill(),fill_n()。如果不是,则调用construct().

 

posted on 2017-12-06 08:54  pan.panda  阅读(534)  评论(0编辑  收藏  举报