从零开始学C++之STL(二):实现简单容器模板类Vec(vector capacity 增长问题、allocator 内存分配器)

首先,vector 在VC 2008 中的实现比较复杂,虽然vector 的声明跟VC6.0 是一致的,如下:

 C++ Code 
1
2
template <  class _Ty,  class _Ax = allocator<_Ty> >
class vector;

但在VC2008 中vector 还有基类,如下:

 C++ Code 
1
2
3
4
5
6
7
// TEMPLATE CLASS vector
template <  class _Ty,
          class _Ax >
class vector
    :  public _Vector_val<_Ty, _Ax>
{
};

稍微来看一下基类_Vector_val:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// TEMPLATE CLASS _Vector_val
template <  class _Ty,
          class _Alloc >
class _Vector_val
    :  public _CONTAINER_BASE_AUX_ALLOC<_Alloc>
{
     // base class for vector to hold allocator _Alval
protected:
    _Vector_val(_Alloc _Al = _Alloc())
        : _CONTAINER_BASE_AUX_ALLOC<_Alloc>(_Al), _Alval(_Al)
    {
         // construct allocator from _Al
    }

     typedef  typename _Alloc:: template
    rebind<_Ty>::other _Alty;

    _Alty _Alval;    // allocator object for values
};

为了理解_Alty 的类型,还得看一下allocator模板类:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template< class _Ty>  class allocator
{

     template<>  class _CRTIMP2_PURE allocator< void>
    {
         // generic allocator for type void
     public:
         template< class _Other>
         struct rebind
        {
             // convert an allocator<void> to an allocator <_Other>
             typedef allocator<_Other> other;
        };
        ....
    };
    ...
};

typedef typename _Alloc::template rebind<_Ty>::other _Alty; 整体来看是类型定义,假设现在我们这样使用


vector<int>, 那么_Ty 即 int, _Ax 即 allocator<int>,由vector 类传递给 基类_Vector_val,则_Alloc 即


 allocator<int> ;可以看到 allocator<void> 是allocator 模板类的特化, rebind<_Ty> 是成员模板类,other是成员模板类


中自定义类型,_Ty 即是int , 那么other 类型也就是allocator<int>, 也就是说_Alty 是类型 allocator<int> 。


_Alty _Alval; 即 基类定义了一个allocator<int> 类型的成员,被vector 继承后以后用于为vector 里面元素分配内存等操作。


如 iterator new_data  = alloc.allocate(new_size); 注意,标准的vector::iterator 是以模板类实现的,下面的实现简单地将其等同为指


针,实际上真正的iterator 类的实现是内部有一个指针成员,指向容器元素。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值