简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM