push_back vs emplace_back

后端 未结 7 2380
南旧
南旧 2020-11-22 03:41

I\'m a bit confused regarding the difference between push_back and emplace_back.

void emplace_back(Type&& _Val);
void push_         


        
7条回答
  •  春和景丽
    2020-11-22 03:48

    emplace_back conforming implementation will forward arguments to the vector::value_typeconstructor when added to the vector. I recall Visual Studio didn't support variadic templates, but with variadic templates will be supported in Visual Studio 2013 RC, so I guess a conforming signature will be added.

    With emplace_back, if you forward the arguments directly to vector::value_type constructor, you don't need a type to be movable or copyable for emplace_back function, strictly speaking. In the vector case, this is not useful, since vector::value_type needs a copyable or movable type to grow.

    But note that this could be useful for std::map, since once you allocate an entry in the map, it doesn't need to be moved or copied ever anymore, unlike with vector, meaning that you can use std::map effectively with a mapped type that is neither copyable nor movable.

    提交回复
    热议问题