#include <iostream>
#include <vector>
class Example
{
public:
int a_;
Example(int a)
{
a_ = a;
}
Example(const Example &other)
{
printf("Copy constructor of %d\n", other.a_);
a_ = other.a_;
}
};
int main()
{
std::vector<Example> myvector;
Example example1(1);
Example example2(2);
myvector.push_back(example1);
myvector.push_back(example2);
return 1;
}
You will get this output :
1 2 3
Copy constructor of 1
Copy constructor of 2
Copy constructor of 1
Why the the copy constructor of '1' is exectued two times and copy constructor of '2' only once??
Actually I don't know that I am right ... I'm sure that the issue is to do with resizing, but I'm hazy on which type of constructor (copy, move, ... ) would be called at that point.
always resize the vector whenever possible
Actually, I wouldn't! I only put that there to determine if it was something to do with the resizing. I wouldn't advocate it in general: just live with the fact that the copy constructor gets called a few extra times. Often/mostly you wouldn't know what size to reserve.