简体   繁体   English

C ++为什么向量初始化会调用复制构造函数

[英]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. 它调用默认构造函数一次,然后再调用复制构造函数10次。 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. 除了你指定的初始大小为10之外,它将分配没有对象的内存,因此它必须创建10个对象。 If you want memory for 10 objects without actually creating them, you can do something like: 如果您想要10个对象的内存而不实际创建它们,您可以执行以下操作:

 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. 如果未指定值,则会创建一个(使用默认ctor)传递给ctor,然后在向量本身中复制该值。

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). 没有真正的问题,它可以做其他事情,但这提供了简单(不指定值),多功能性(如果你想要指定一个值)和代码大小之间的合理平衡(避免重复整个ctor只是为了默认构建内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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