What is difference between insert and emplace for

2019-04-09 05:41发布

问题:

This question already has an answer here:

  • push_back vs emplace_back 6 answers
  • C++ std::vector emplace vs insert [duplicate] 2 answers

Apart from single insertion using emplace and multiple insertion using insert in vector, is there any other difference in their implementation?

As in both cases inserting any element will shift all other elements.

回答1:

std::vector::insert copies or moves the elements into the container by calling copy constructor or move constructor.
while,
In std::vector::emplace elements are constructed in-place, i.e. no copy or move operations are performed.

The later was introduced since C++11 and its usage is desirable if copying your class is a non trivial operation.



回答2:

The primary difference is that insert takes an object whose type is the same as the container type and copies that argument into the container. emplace takes a more or less arbitrary argument list and constructs an object in the container from those arguments.



标签: c++ vector