When you initialize a vector in the following way:
std::vector<MyClass> MyVec(10);
It calls the default constructor once and then calls the copy constructor an additional 10 times. So, if I understand it correctly, the objects in the vector are all made by the copy constructor.
Can someone explain the reason for calling the copy constructor and not the default one? Or even just allocating the memory without the objects?
In other words, a good compiler will not create a copy for copy-initialization when it can be avoided; instead it will just call the constructor directly -- ie, just like for direct-initialization.
A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object.
The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.
It will allocate memory without objects, except that you've specified an initial size of 10, so it has to create 10 objects. If you want memory for 10 objects without actually creating them, you can do something like:
std::vector<MyClass> MyVec;
MyVec.reserve(10);
If you look the signature of the constructor you're using is something like:
vector(size_t num, T initial_value = T());
That let's you pass a value to use to fill the spots you tell it to create. If you don't specify a value, it creates one (with the default ctor) to pass to the ctor, and then makes copies of that in the vector itself.
There's no real question that it could do other things, but that provides a reasonable balance between simplicity (don't specify a value), versatility (specify a value if you want), and code size (avoid duplicating the entire ctor just to default construct the contents).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With