在SGI STL的实现中,vector的push_back函数不使用默认参数

时间:2016-12-30 03:20:37

标签: c++ stl sgi

最近,我阅读了SGI STL源并遇到了一个问题。为什么sgi stl 在vector的push_back上使用重载函数而不是默认参数。这是关于push_back的SGI STL源。

void push_back(const _Tp& __x) {
if (_M_finish != _M_end_of_storage) {
    construct(_M_finish, __x);
    ++_M_finish;
}
else
    _M_insert_aux(end(), __x);
}
void push_back() {
    if (_M_finish != _M_end_of_storage) {
        construct(_M_finish);
        ++_M_finish;
    }
    else
        _M_insert_aux(end());
}

但我不知道为什么不将默认参数用作休闲。

void push_back(const _Tp& __x = _Tp()) {
if (_M_finish != _M_end_of_storage) {
  construct(_M_finish, __x);
  ++_M_finish;
}
else
  _M_insert_aux(end(), __x);
}

例外,_M_insert_aux函数也有重载函数作为fallowed。 * __ position = _Tp()使用默认构造函数。我不知道为什么不使用默认参数

template <class _Tp, class _Alloc>
void
vector<_Tp, _Alloc>::_M_insert_aux(iterator __position)
{
  if (_M_finish != _M_end_of_storage) {
    construct(_M_finish, *(_M_finish - 1));
    ++_M_finish;
    copy_backward(__position, _M_finish - 2, _M_finish - 1);
    *__position = _Tp();
  }
  else {
    const size_type __old_size = size();
    const size_type __len = __old_size != 0 ? 2 * __old_size : 1;
    iterator __new_start = _M_allocate(__len);
    iterator __new_finish = __new_start;
    __STL_TRY {
      __new_finish = uninitialized_copy(_M_start, __position, __new_start);
      construct(__new_finish);
      ++__new_finish;
      __new_finish = uninitialized_copy(__position, _M_finish, __new_finish);
    }
    __STL_UNWIND((destroy(__new_start,__new_finish),
                  _M_deallocate(__new_start,__len)));
    destroy(begin(), end());
    _M_deallocate(_M_start, _M_end_of_storage - _M_start);
    _M_start = __new_start;
    _M_finish = __new_finish;
    _M_end_of_storage = __new_start + __len;
  }
}

1 个答案:

答案 0 :(得分:1)

如果类型没有默认构造函数,则带有默认参数的版本将无效,这将导致无法对此类型使用push_back。模板将具有替换失败。使用两个函数可以将替换失败与其中一个函数隔离开来。