好记性不如铅笔头

C && C++, C++ STL, 编程

C++ STL读书笔记:stl_vector.h

备注:

本读书笔记基于侯捷先生的《STL源码剖析》,截图和注释版权均属于原作者所有。
本读书笔记中的源码部分直接拷贝自SGI-STL,部分代码删除了头部的版权注释,但代码版权属于原作者。
小弟初看stl,很多代码都不是太懂,注释可能有很多错误,还请路过的各位大牛多多给予指导。
为了降低学习难度,作者这里换到了SGI-STL-2.91.57的源码来学习,代码下载地址为【 http://jjhou.boolan.com/jjwbooks-tass.htm

stl_vector.h:

部分代码如下,去掉了文件头部的注释。

//默认使用alloc作为空间构造器,其实就是new,delete。
template <class T, class Alloc = alloc>
class vector {
public:
	//由于vector在内存中的排放类似于数组,因此迭代器,引用均可以直接使用vector存储的类型。
  typedef T value_type;
  typedef value_type* pointer;
  typedef const value_type* const_pointer;
  typedef value_type* iterator;
  typedef const value_type* const_iterator;
  typedef value_type& reference;
  typedef const value_type& const_reference;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;

#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
  typedef reverse_iterator<const_iterator> const_reverse_iterator;
  typedef reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
  typedef reverse_iterator<const_iterator, value_type, const_reference, 
                           difference_type>  const_reverse_iterator;
  typedef reverse_iterator<iterator, value_type, reference, difference_type>
          reverse_iterator;
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
protected:
  typedef simple_alloc<value_type, Alloc> data_allocator;
  iterator start;//起始内容指针
  iterator finish;//终止内容指针
  iterator end_of_storage;//存储空间的最后位置指针
  void insert_aux(iterator position, const T& x);
  void deallocate() {
  	//当空间被销毁时,从起始点开始销毁,销毁个数为存储空间个数。
    if (start) data_allocator::deallocate(start, end_of_storage - start);
  }
//申请一块可以容纳n个T的空间,然后全部赋值为value
  void fill_initialize(size_type n, const T& value) {
    start = allocate_and_fill(n, value);//内存申请好之后,起始地址就是起始内容指针
    finish = start + n;//终止内容指针为起始指针 + n (可以参考数组)
    end_of_storage = finish;//由于空间是刚刚申请的,因此空间的最后位置就是终止内容的位置
  }
public:
	//以下为各种get操作,返回的是起始位置,终止位置,以及空间个数
  iterator begin() { return start; }
  const_iterator begin() const { return start; }
  iterator end() { return finish; }
  const_iterator end() const { return finish; }
  reverse_iterator rbegin() { return reverse_iterator(end()); }
  const_reverse_iterator rbegin() const { 
    return const_reverse_iterator(end()); 
  }
  reverse_iterator rend() { return reverse_iterator(begin()); }
  const_reverse_iterator rend() const { 
    return const_reverse_iterator(begin()); 
  }
  //返回当前已经存储的空间的数目
  size_type size() const { return size_type(end() - begin()); }
  //由于vector的空间是动态扩充的,因此不存在最大值,这里就将最大值设为当
  //全部内存耗尽时,能存储的空间数目
  size_type max_size() const { return size_type(-1) / sizeof(T); }
  //返回当前容量,由于vector动态扩充时会多申请一部分内存,因此这里需要使用存储空间的最后位置来
  //计算
  size_type capacity() const { return size_type(end_of_storage - begin()); }
  bool empty() const { return begin() == end(); }
  //vector在内存中是连续存放的,因此可以通过内存操作获取指定位置的内容
  reference operator[](size_type n) { return *(begin() + n); }
  const_reference operator[](size_type n) const { return *(begin() + n); }


//构造函数,初始化时,起始点=终止点=存储空间最后点=0,此时并不分配内存
  vector() : start(0), finish(0), end_of_storage(0) {}
  	
//构造函数,构造后就有n个T,每个T都被赋值为value,因此这里调用了fill_initialize	
  vector(size_type n, const T& value) { fill_initialize(n, value); }
  vector(int n, const T& value) { fill_initialize(n, value); }
  vector(long n, const T& value) { fill_initialize(n, value); }
  explicit vector(size_type n) { fill_initialize(n, T()); }

//拷贝构造函数,直接将原vector(即x)的有效内容拷贝过来
  vector(const vector<T, Alloc>& x) {
    start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
    finish = start + (x.end() - x.begin());
    end_of_storage = finish;
  }
#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  vector(InputIterator first, InputIterator last) :
    start(0), finish(0), end_of_storage(0)
  {
    range_initialize(first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */
  vector(const_iterator first, const_iterator last) {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }
#endif /* __STL_MEMBER_TEMPLATES */
  ~vector() { 
    destroy(start, finish);
    deallocate();
  }
  vector<T, Alloc>& operator=(const vector<T, Alloc>& x);

//扩充容量至n,如果当前容量>n了,那么什么也不做
  void reserve(size_type n) {
    if (capacity() < n) {
    	//当前容量<n时
      const size_type old_size = size();
      //先申请一块新的内存,容量为n,然后将当前的有效数据拷贝过去
      iterator tmp = allocate_and_copy(n, start, finish);
      //将原有的内存上的有效数据销毁(调用析构函数)
      destroy(start, finish);
      //释放原有内存
      deallocate();
      //将start,finish,end_of_storage赋值为新内存的值
      start = tmp;
      finish = tmp + old_size;
      end_of_storage = start + n;
    }
  }
  //返回第一个和最后一个有效数据的引用,这里注意的是finish指向的是
  //最后的有效数据的下一个,因此返回最后一个有效数据时,finish需要 -1
  reference front() { return *begin(); }
  const_reference front() const { return *begin(); }
  reference back() { return *(end() - 1); }
  const_reference back() const { return *(end() - 1); }
 
	//在vector的最后在添加一个T,内容为x
  void push_back(const T& x) {
  	//如果终止内容指针 != 存储空间最后指针,说明之前申请的内存还没有用完,
  	//因此可以直接在终止内容指针上进行赋值,然后终止内容指针向前 + 1
    if (finish != end_of_storage) {
      construct(finish, x);
      ++finish;
    }
    else
    //如果终止内容指针=存储空间最后指针,那么说明之前申请的内存已经用完了,
    //根据vector的内存策略,必须重新申请内存。
      insert_aux(end(), x);
  }
  void swap(vector<T, Alloc>& x) {
    __STD::swap(start, x.start);
    __STD::swap(finish, x.finish);
    __STD::swap(end_of_storage, x.end_of_storage);
  }
  //在指定位置上插入一个T,内容为x
  iterator insert(iterator position, const T& x) {
    size_type n = position - begin();
//首先判断这个指定位置是不是终止内容指针,如果是终止内容指针,而且之前申请的内存还没有用完,
//就直接在终止内容指针上进行赋值,然后终止内容指针向前 + 1
    if (finish != end_of_storage && position == end()) {
      construct(finish, x);
      ++finish;
    }
    else
//如果当前的位置不是最后的位置,或者内存用完了,就只能重新申请内存。
      insert_aux(position, x);

//返回插入的位置
    return begin() + n;
  }
  iterator insert(iterator position) { return insert(position, T()); }
#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void insert(iterator position, InputIterator first, InputIterator last) {
    range_insert(position, first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */
  void insert(iterator position,
              const_iterator first, const_iterator last);
#endif /* __STL_MEMBER_TEMPLATES */

  void insert (iterator pos, size_type n, const T& x);
  void insert (iterator pos, int n, const T& x) {
    insert(pos, (size_type) n, x);
  }
  void insert (iterator pos, long n, const T& x) {
    insert(pos, (size_type) n, x);
  }

//从最后边删除一个T,这里仅仅调用析构函数,并不释放内存
  void pop_back() {
    --finish;
    destroy(finish);
  }
//在指定位置删除一个T  
  iterator erase(iterator position) {
//如果要删除的T不是在最后,那么需要将其后面的所有内容全部向前复制一个,这里
//使用的是copy函数,copy函数会将要覆盖的内容先销毁掉,然后把新的内容复制过去
    if (position + 1 != end())
      copy(position + 1, finish, position);
//当copy调用完成后,最后的那个有效数据就有两份了(一份是之前存在的,一份是刚刚拷贝的)
//那么这里就需要把最后边的那个之前存在的给销毁,顺便更新指针。
    --finish;
    destroy(finish);
    return position;
  }
//删除指定位置区间的所有元素
  iterator erase(iterator first, iterator last) {
//这里使用的是copy函数,后面笔记  	
    iterator i = copy(last, finish, first);
    destroy(i, finish);
    finish = finish - (last - first);
    return first;
  }
//重新设置vector的大小
//如果当前有效数据的数目>新设置的数目,那么多出来的数据会被删除
//如果当前有效数据的数目<新设置的数目,那么就在vector的尾部添加元素,并赋值为x
  void resize(size_type new_size, const T& x) {
    if (new_size < size()) 
      erase(begin() + new_size, end());
    else
      insert(end(), new_size - size(), x);
  }
  void resize(size_type new_size) { resize(new_size, T()); }
  void clear() { erase(begin(), end()); }

protected:
	//申请一块能容纳n个T的内存,然后每个T都赋值为x
  iterator allocate_and_fill(size_type n, const T& x) {
//申请内存
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
//调用拷贝构造函数
      uninitialized_fill_n(result, n, x);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }

#ifdef __STL_MEMBER_TEMPLATES
  template <class ForwardIterator>
  iterator allocate_and_copy(size_type n,
                             ForwardIterator first, ForwardIterator last) {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#else /* __STL_MEMBER_TEMPLATES */
  iterator allocate_and_copy(size_type n,
                             const_iterator first, const_iterator last) {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#endif /* __STL_MEMBER_TEMPLATES */


#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void range_initialize(InputIterator first, InputIterator last,
                        input_iterator_tag) {
    for ( ; first != last; ++first)
      push_back(*first);
  }

  // This function is only called by the constructor.  We have to worry
  //  about resource leaks, but not about maintaining invariants.
  template <class ForwardIterator>
  void range_initialize(ForwardIterator first, ForwardIterator last,
                        forward_iterator_tag) {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }

  template <class InputIterator>
  void range_insert(iterator pos,
                    InputIterator first, InputIterator last,
                    input_iterator_tag);

  template <class ForwardIterator>
  void range_insert(iterator pos,
                    ForwardIterator first, ForwardIterator last,
                    forward_iterator_tag);

#endif /* __STL_MEMBER_TEMPLATES */
};

template <class T, class Alloc>
//判断两个vector是否相等,判断里面的每个数据是否相同
inline bool operator==(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return x.size() == y.size() && equal(x.begin(), x.end(), y.begin());
}

template <class T, class Alloc>
inline bool operator<(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class T, class Alloc>
inline void swap(vector<T, Alloc>& x, vector<T, Alloc>& y) {
  x.swap(y);
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

//vector的赋值构造函数
template <class T, class Alloc>
vector<T, Alloc>& vector<T, Alloc>::operator=(const vector<T, Alloc>& x) {
  if (&x != this) {
  	//如果x的有效元素的个数大于当前的容量,
  	//那就只能先申请一块新的内存,用来存放x的所有数据,
  	//然后释放掉本地的空间
    if (x.size() > capacity()) {
      iterator tmp = allocate_and_copy(x.end() - x.begin(),
                                       x.begin(), x.end());
      destroy(start, finish);
      deallocate();
      start = tmp;
      end_of_storage = start + (x.end() - x.begin());
    }
    //如果当前的有效数据个数>x,那么就将x的所有数据复制到本地,覆盖本地已有的数据
    //然后销毁掉本地的剩余有效数据
    else if (size() >= x.size()) {
      iterator i = copy(x.begin(), x.end(), begin());
      destroy(i, finish);
    }

    //如果当前的有效数据个数<x,但是本地有足够的存储空间,那么就将x的所有数据复制到本地,覆盖本地已有的数据
    else {
      copy(x.begin(), x.begin() + size(), start);
      uninitialized_copy(x.begin() + size(), x.end(), finish);
    }
    finish = start + x.size();
  }
  return *this;
}

template <class T, class Alloc>
//在指定位置插入一个T,
void vector<T, Alloc>::insert_aux(iterator position, const T& x) {
//如果finish != end_of_storage,说明本地至少还有一个未使用的内存空间
  if (finish != end_of_storage) {
//先把vector的最后面的那个有效数据重新构造一个,放到最后。,这里主要是为了满足
//copy_backward的调用条件
    construct(finish, *(finish - 1));
    ++finish;
    T x_copy = x;
//将position后的所有有效数据(除了最后的那个刚刚构造出来的)全部向后复制一个位置
    copy_backward(position, finish - 2, finish - 1);
//然后将空出来的position的内存赋值为x,这里会调用到T的拷贝构造函数
    *position = x_copy;
  }
  else {
//当本地没有可用的内存空间时,需要申请一份新的内存,这里采取的策略是申请一块原有内存的2倍大的内存  	
    const size_type old_size = size();
    const size_type len = old_size != 0 ? 2 * old_size : 1;
//申请内存
    iterator new_start = data_allocator::allocate(len);
    iterator new_finish = new_start;
    __STL_TRY {
//先将 position 之前的数据拷贝到新的内存空间里
      new_finish = uninitialized_copy(start, position, new_start);
//然后在position位置上使用x构造新的数据
      construct(new_finish, x);
      ++new_finish;
//最后将position之后的数据拷贝到新的内存空间中
      new_finish = uninitialized_copy(position, finish, new_finish);
    }

#       ifdef  __STL_USE_EXCEPTIONS 
    catch(...) {
//出异常了!!
//将拷贝的数据全部销毁掉
      destroy(new_start, new_finish); 
//将新申请的内存释放掉
      data_allocator::deallocate(new_start, len);
//把异常扔出去
      throw;
    }
#       endif /* __STL_USE_EXCEPTIONS */
//将原有的数据销毁掉
    destroy(begin(), end());
//将原有的内存释放掉    
    deallocate();

//根据新的内存更新指针
    start = new_start;
    finish = new_finish;
    end_of_storage = new_start + len;
  }
}

template <class T, class Alloc>
//和上面的insert_aux函数差不多
void vector<T, Alloc>::insert(iterator position, size_type n, const T& x) {
  if (n != 0) {
  	//如果剩余的未使用的内存数量>=n,说明不需要重新申请新的内存
    if (size_type(end_of_storage - finish) >= n) {
      T x_copy = x;
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        fill(position, position + n, x_copy);
      }
      else {
        uninitialized_fill_n(finish, n - elems_after, x_copy);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        fill(position, old_finish, x_copy);
      }
    }
    else {
      const size_type old_size = size();        
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_fill_n(new_finish, n, x);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef  __STL_USE_EXCEPTIONS 
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

#ifdef __STL_MEMBER_TEMPLATES

template <class T, class Alloc> template <class InputIterator>
void vector<T, Alloc>::range_insert(iterator pos,
                                    InputIterator first, InputIterator last,
                                    input_iterator_tag) {
  for ( ; first != last; ++first) {
    pos = insert(pos, *first);
    ++pos;
  }
}

template <class T, class Alloc> template <class ForwardIterator>
void vector<T, Alloc>::range_insert(iterator position,
                                    ForwardIterator first,
                                    ForwardIterator last,
                                    forward_iterator_tag) {
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        ForwardIterator mid = first;
        advance(mid, elems_after);
        uninitialized_copy(mid, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, mid, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

#else /* __STL_MEMBER_TEMPLATES */

template <class T, class Alloc>
void vector<T, Alloc>::insert(iterator position, 
                              const_iterator first, 
                              const_iterator last) {
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        uninitialized_copy(first + elems_after, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, first + elems_after, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

备注:

关于 copy 和 copy_backward,个人的总结如下,不知道对不对。
如果是简单类型或者存储内容不复杂(拷贝,赋值等简单),那么stl底层copy会直接调用memmove,上层vector代码也不用担心析构函数的处理。
如果存储内容类比较复杂,这里stl底层copy会循环进行赋值操作,不会调用析构函数,此时类内部资源的释放就需要依靠赋值构造函数来处理。

发表评论

3 × 4 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据