c++stlsgi

In the implement of SGI STL, push_back function of vector not use default parameter


Recently, I read SGI STL source and meet a fallowed question.Why sgi stl use overloaded function on push_back of vector instead of default parameter.This is the SGI STL source about push_back.

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());
}

But I don't know why not use the default parameter as fallow.

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

Exceptional, _M_insert_aux function also have overloaded function as fallowed. *__position = _Tp() use default construct function. I don't know why not use default parameter.

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;
  }
}

Solution

  • The version with a default parameter will not work if the type does not have a default constructor, which would make it impossible to use push_back with such types. The template will have a substitution failure. Using two functions allows you to isolate the substitution failure to one of the functions.