emplace_back能就地通過參數構造對象,不需要拷貝或者移動內存,相比push_back能更好地避免內存的拷貝與移動,使容器插入元素的性能得到進一步提升。在大多數情況下應該優先使用emplace_back來代替push_back。
vector push_back 源碼實現:
void push_back(const value_type &__x) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; } }
vector emplace_back 源碼實現:
template <typename _Tp, typename _Alloc> template <typename... _Args> void vector<_Tp, _Alloc>:: emplace_back(_Args &&... __args) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish; } else _M_emplace_back_aux(std::forward<_Args>(__args)...); }
利用了c++ 11的新特性變長參數模板(variadic template),直接構造了一個新的對象,不需要拷貝或者移動內存,提高了效率。
std::forward<_Args>(__args)...