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?
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.
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.
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.
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.
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)
There are actually two things happening in emplace_back:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With