STL源码剖析之vector
vector的数据安排以及操作方式,与array非常相似。两者的唯一差别在于空间的运用的灵活性,array是静态的,一旦配置了就不能改变,而 vector是动态
试读章节 · 登录解锁全文
1.5 小时
STL源码剖析之vector
0.导语
vector的数据安排以及操作方式,与array非常相似。两者的唯一差别在于空间的运用的灵活性,array是静态的,一旦配置了就不能改变,而 vector是动态空间,随着元素的加入,它的内部机制会自行扩充空间以容纳新元素。下面一起来看一下vector的"内部机制",怎么来实现空间配置策略的。
1.vector
在_Vector_base中开头有两行比较难理解,下面一个一个分析:
1.1 _Tp_alloc_type
开头处定义:
typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type;
在__gnu_cxx::__alloc_traits中:对应文件为:ext/alloc_traits.h
template<typename _Tp>
struct rebind
{ typedef typename _Base_type::template rebind_alloc<_Tp> other; };
等价于
typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other
等价于:
typename _Base_type::template rebind_alloc<_Tp>
而_Base_type是:
typedef std::allocator_traits<_Alloc> _Base_type;
所以上述等价于:
typename std::allocator_traits<_Alloc>::template rebind_alloc<_Tp>
继续到allocator_traits中寻找
找到了:
template<typename _Up>
using rebind_alloc = allocator<_Up>;
于是:
std::allocator_traits<_Alloc>::template rebind_alloc<_Tp>
等价于:
allocator<_Tp>
小结
typedef typename __gnu_c
…