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?
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.
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.
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.
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.
Besides the point others mentioned, it would also require changing the old interface. And there are times when that's simply not acceptable.
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