Unnecessary calls to copy constructor when creating std::vector
I created a vector as
std::vector<MyClass> my_vec(3);
I expected that this to call the default constructor for MyClass 3 times.Instead it called the default constructor once and the copy constructor 3 time.In other words, it was creating a MyClass object and then copying it to each element of the vector.
This seems inefficient.But more importantly for me, it led to a crash.This was because we set an fpu control flag that causes an exception when aNaN is copied. And MyClass contained a double that was not initialised and happened to default toNan.
Given that I can’t changing MyClass, is there a way round this problem? One possibility would be to recode the vector constructor.I do not feel confident about doing this. Has anyone else tried?
AFAIK you can not make any assumption how the elements are constructed. The standard says only that there must be a default constructor, so IMHO it is legal to do the initialization in this way.
Also remember that your default constructor does a bad job. You can not assume that elelemts are not copied by vector, in this case an exception would be thrown to. Its the implementor of the STL to control how to do and manage objects.
Also what is inefficient. Either usingthe default constructor or a copy constructor depends strongly on the class of what is efficient.
Martin
The std::vector behaviour may be legal, but it is not optimal. For some classes, a copy constructor will be slower than a default constructor, and for very few classes will it be the other way round. I strongly suspect that the reason for the current behaviour is that it was easy to implement.