Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move with vector::push_back

Tags:

c++

c++11

Suppose I have the following code:

#include <vector> struct A {     int a;     int x; }; int main() {     using namespace std;     A a1;     A a2;     vector<A> va;     va.push_back(a1);     va.push_back(move(a2)); } 

I am aware that the elements of std::vector are stored contiguously, unlike a std::list. In the above code a2 is moved but is there really no copying of a2 to the vector va? What is the difference between va.push_back(a2); and va.push_back(move(a2));?

like image 303
ggg Avatar asked Jul 20 '12 03:07

ggg


People also ask

Does Push_back copy or move?

Since C++11, push_back will perform a move instead of a copy if the argument is an rvalue reference.

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.

Does Emplace_back copy or move?

Calling emplace_back will call the move constructor of std::string when std::move is used, which could save on a copy (so long as that string isn't stored in a SSO buffer). Note that this is essentially the same as push_back in this case.


1 Answers

In your case, there is no effective difference, since you are using compiler-provided copy constructors. You would see a noticeable performance difference when using objects that are move-constructible, and take a lot of effort to copy. In that case, using push_back(x) would create a copy of the object, while push_back(move(x)) would tell push_back() that it may "steal" the contents of x, leaving x in an unusable and undefined state.

Consider if you had a vector of lists (std::vector<std::list<int> >) and you wanted to push a list containing 100,000 elements. Without move(), the entire list structure and all 100,000 elements will be copied. With move(), some pointers and other small bits of data get shuffled around, and that's about it. This will be lots faster, and will require less overall memory consumption.

like image 189
cdhowie Avatar answered Sep 24 '22 08:09

cdhowie