其实空间配置器(allocator)可能是最不需要介绍的组件,它总是隐藏在容器的背后,整个STL的操作对象(所有的数值)都存放在容器之内,而容器一定需要配置空间以放置资料。
需要注意的是:allocator不单单只是指内存配置器,空间不一定是内存,也可以是磁盘或其它辅助存储介质,当然,我们最常用的就是内存。
1,空间配置器的标准接口
根据STL规范,下面列出allocator的必要接口:
allocator::value_type
allocator::pointer
allocator::const_pointer
allocator::reference
allocator::const_reference
allocator::size_type
allocator::difference_type
allocator::rebind
allocator::allocator()
default constructor
allocator::allocator(const allocator&)
2,结构
STL标准规范告诉我们,配置器定义于< memory >之中,在这个文件中包含两个文件:
#include <stl_alloc.h> //负责内存空间的配置与释放
#include <stl_construct.h> //负责对象内容的构造与析构
结构如图所示:
3,内存基本处理工具
在STL中共定义了五个全局函数作用于未初始化的空间上,这对容器非常有帮助。
一,构造和析构的基本工具:construct()和destroy()
下面是< stl_condtruct.h >的部分内容
#include<new.h>
template <class T1,class T2>
inline void construct(T1* p,const T2& value) {
new (p) T1(value); //placement new;调用 T1::T1(value);
}
template <class T>
inline void destroy(T* pointer){
pointer-~T(); //调用dtor ~T()
可以参考下图:
二,另外三个函数:uninitialized_copy(),uninitialized_fill(),uninitialized_fill_n()
这三个函数分别对应于高层次函数copy(),fill(),fill_n(),这些都是STL算法里面的,在后面将会介绍。如果你要使用这三个低层次函数,你需要包含头文件< memory >。
2.1 uninitialized_copy
template< class Inputiterator, class Forwarditerator>
ForwardIterator
uninitialized_copy(InputIterator first , InputIterator last, ForwardIterator result);
如果你需要实现一个容器,UNinitialized_copy()这样的函数会为你带来很多方便,因为容器的全区间构造函数通常以两个步骤完成:
(1)配置内存区块,足以包含范围内的所有元素
(2)使用uninitialized_copy(),在该内存区块上构造函数
解析:
本函数接收三个参数:
(1)迭代器first指向输入端的起始处
(2)迭代器last指向输入端的结束处
(3)迭代器result指向输出端的起始处
2.2 uninitialized_fill
template< class ForwardIterator, class T>
uninitialized_fill(ForwardIterator first , ForwardIterator last,const T&x);
解析:
本函数接收三个参数:
(1)迭代器first指向输出端的起始处
(2)迭代器last指向输出端的结束处
(3)x表示初值
2.3 uninitialized_fill_n
template< class ForwardIterator, class Size, class T>
ForwardIterator
uninitialized_fill_n(ForwardIterator first , Size n, const T& x);
解析:
本函数接收三个参数:
(1)迭代器first指向欲初始化空间的起始处
(2)n表示欲初始化空间的大小
(3)x表示初值