Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector's emplace_back

Tags:

c++

c++11

stl

Can you please explain how "perfect forwarding" works?

I read that vector's emplace_back doesn't need to copy nor move objects, because its argument is implemented as variadic template.

std::vector<T>::emplace_back(_Args&&... __args)

Can you describe it in more detail? Why won't it copy nor move?

like image 284
user1494506 Avatar asked Jul 09 '12 10:07

user1494506


People also ask

What is Emplace_back in vector?

C++ Vector Library - emplace_back() Function The C++ function std::vector::emplace_back() inserts new element at the end of vector. Reallocation happens if there is need of more space. This method increases container size by one.

Should I use Push_back or Emplace_back?

Specific use case for emplace_back : If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back . It will create the object in-place within the container. Notes: push_back in the above case will create a temporary object and move it into the container.

Is Emplace_back faster than Push_back?

Google also gives this and this questions. I decided to compare them for a vector that would be filled by integers. The result is that emplace_back is faster. push_back took me 2.76127 seconds.

Should I use std :: move with Emplace_back?

emplace_back(std::move(w)); I recommend sticking with push_back for day-to-day use. You should definitely use emplace_back when you need its particular set of skills — for example, emplace_back is your only option when dealing with a deque<mutex> or other non-movable type — but push_back is the appropriate default.


2 Answers

emplace_back directly constructs the element at the correct position in the vector. Think of it as if

vector<T> v;
v.emplace_back(a,b,c);

is transformed into (idx being the new index)

new (v.data()+idx) T(a,b,c);

(The reality is a bit more complex involving forwarding the arguments as std::forward<_Args>()... but that might be more confusing to get the key of emplace operations)

like image 53
PlasmaHH Avatar answered Oct 13 '22 02:10

PlasmaHH


There are actually two things happening in emplace_back:

  1. You don't pass an object of type T but arguments to a constructor of T. This way, object construction is delayed: the vector is extended to accomodate for the memory needed by the new object, and the constructor is called to initialized the object in the vector. Variadic template don't have anything to do with copies, they only allow forwarding a variable number of arguments to the constructor.
  2. Arguments to the constructors themselves are not copied because they are passed as rvalues references and std::move is used to forward them to the constructor. Basically, move semantics avoid deep copies of objects.
like image 28
Antoine Avatar answered Oct 13 '22 01:10

Antoine