vector push_back calling copy_constructor more than once?

What happens:

  1. x is inserted via push_back. One copy occurs: The newly created element is initialized with the argument. my_int is taken over as zero because xs default constructor initialized it so.

  2. The second element is push_back‘d; The vector needs to reallocate the memory since the internal capacity was reached.
    As no move constructor is implicitly defined for Myint1 the copy constructor is chosen; The first element is copied into the newly allocated memory (its my_int is still zero… so the copy constructor shows my_int as 0 again) and then x is copied to initialize the second element (as with the first in step 1.). This time x has my_int set to one and that’s what the output of the copy constructor tells us.

So the total amount of calls is three. This might vary from one implementation to another as the initial capacity might be different. However, two calls are be the minimum.

You can reduce the amount of copies by, in advance, reserving more memory – i.e. higher the vectors capacity so the reallocation becomes unnecessary:

myints.reserve(2); // Now two elements can be inserted without reallocation.

Furthermore you can elide the copies when inserting as follows:

myints.emplace_back(0);

This “emplaces” a new element – emplace_back is a variadic template and can therefore take an arbitrary amount of arguments which it then forwards – without copies or moves – to the elements constructor.

1 Because there is a user-declared copy constructor.

Leave a Comment