10

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.

Ambar
  • 112
  • 11
Sandeepjn
  • 181
  • 1
  • 1
  • 7

2 Answers2

19

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.

johan
  • 1,664
  • 2
  • 14
  • 30
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • How does `emplace` work behind the scenes? How can I emulate its behavior myself? – David G Mar 27 '13 at 13:05
  • 2
    @David: first off, it's a function template with a parameter pack, so so properly implement/emulate it you need variadic templates (and perfect forwarding). What it actually does is get the necessary memory as normal for a vector and then uses placement new, forwarding its arguments to whatever constructor matches them. I say "uses placement new": it uses the allocator interface but `std::allocator` uses placement new. By contrast `insert` always uses a copy/move ctor, but there could be an implicit conversion before the call, in the case of passing one argument of compatible type. – Steve Jessop Mar 27 '13 at 13:07
3

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165