Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does push_back have two overloads for lvalues and rvalues?

Why would a class/function have two overloads, one for lvalue and one for rvalue?

Eg, from this video, it says we have two overloads for vector<T>::push_back

void push_back( const T& value );
void push_back( T&& value );

Why can't we have just one overload by value,

void push_back( T value );

If it was an lvalue, value would be copied and if it was an rvalue, value would be moved. Isn't this the way how it works and guaranteed by the standard?

like image 781
balki Avatar asked Jan 26 '13 07:01

balki


People also ask

Should I use emplace_ back or push_ back?

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. One reason is that emplace_back is more work for the compiler.

When should I use 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.

Does emplace_ back copy or move?

This code demonstrates that emplace_back calls the copy constructor of A for some reason to copy the first element. But if you leave copy constructor as deleted, it will use move constructor instead.


2 Answers

With your by-value proposition, technically there would be copy+move or move+move, whereas with the other two overloads there is a single copy or a single move.

like image 80
user1610015 Avatar answered Oct 12 '22 23:10

user1610015


Besides the point others mentioned, it would also require changing the old interface. And there are times when that's simply not acceptable.

like image 43
Nicol Bolas Avatar answered Oct 13 '22 01:10

Nicol Bolas