c++ - 在SGI STL的实现中,vector的push_back函数没有使用默认参数

标签 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);
}

异常(exception),_M_insert_aux 函数也有重载函数作为休假。 *__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;
  }
}

最佳答案

如果类型没有默认构造函数,则带有默认参数的版本将无法工作,这将导致无法对此类类型使用 push_back。该模板将出现替换失败。使用两个函数允许您将替换失败隔离到其中一个函数。

关于c++ - 在SGI STL的实现中,vector的push_back函数没有使用默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41390166/

相关文章:

c++ - 在 C++ 中的 main() 之前初始化 vector

c++ - 模板函数和该函数的非模板重载,哪个是最佳匹配?

c++ - 插入失败时列表/ map 返回什么?

c++ - STL 容器元素是否明确要求 (noexcept) 可破坏?

c++ - 成对地遍历一个 vector ,三元组,

c++ - 为什么我不能使用函数适配器 compose2?

c++ - 如何在VS2005中使用sgi hash_table?

c++ - 计时定时器不能正确转换秒数

具有值语义且没有分配器恶作剧的 C++ 数组?

c++ - GLSL 编译失败但没有错误信息