Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Why do vector initialization calls the copy constructor

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?

like image 204
oopsi Avatar asked Sep 08 '12 19:09

oopsi


People also ask

Does copy initialization call copy constructor?

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.

Why copy constructor is called?

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.

What happens if you use the default copy constructor for vector?

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.


1 Answers

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).

like image 129
Jerry Coffin Avatar answered Sep 20 '22 15:09

Jerry Coffin