ggg ggg - 19 days ago 8
C++ Question

Move with vector::push_back

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));
?

Answer

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.