ggg ggg - 1 year ago 197
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;

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download