push

mac2022-06-30  108

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)...

 

转载于:https://www.cnblogs.com/lkpp/p/emplace_back.html

最新回复(0)