What happens:
-
x
is inserted viapush_back
. One copy occurs: The newly created element is initialized with the argument.my_int
is taken over as zero becausex
s default constructor initialized it so. -
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 forMyint
1 the copy constructor is chosen; The first element is copied into the newly allocated memory (itsmy_int
is still zero… so the copy constructor showsmy_int
as0
again) and thenx
is copied to initialize the second element (as with the first in step 1.). This timex
hasmy_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.