未初始化向量中的元素值是什么? [英] What is the element value in an uninitialized vector?

查看:121
本文介绍了未初始化向量中的元素值是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个向量如 vector< myClass> v(10);
每个元素的默认值是什么?

If I create a vector like vector<myClass> v(10); what is the default value of each element?


此外,如果它是一个向量< myUnion> v(10)

Also, what if it is a vector<myUnion> v(10) ?

推荐答案

std :: vector<

The constructor of std::vector<> that you are using when you declare your vector as

vector<myClass> v(10);

实际上有多个参数。它有三个参数:初始大小(您指定为10),新元素的初始值和分配器值。

actually has more than one parameter. It has three parameters: initial size (that you specified as 10), the initial value for new elements and the allocator value.

explicit vector(size_type n, const T& value = T(),
                const Allocator& = Allocator());

第二个和第三个参数有默认参数,这就是为什么你可以省略它们您的声明。

The second and the third parameters have default arguments, which is why you were are able to omit them in your declaration.

新元素的默认参数值是默认参数值,在您的情况下为 MyClass()。此值将通过其副本构造函数复制到所有10个新元素。

The default argument value for the new element is the default-contructed one, which in your case is MyClass(). This value will be copied to all 10 new elements by means of their copy-constructors.

什么 MyClass()意味着取决于你的类。只有你知道。

What exactly MyClass() means depends on your class. Only you know that.

在实现上述接口时,标准库实现允许使用函数重载而不是默认参数。如果一些实现决定使用函数重载,它可能会在 std :: vector 中声明一个只有一个参数(size)的构造函数。这不影响最终结果:所有的矢量元素应该开始他们的生活,如果他们是价值初始化。

P.S. Standard library implementations are allowed to use function overloading instead of default arguments when implementing the above interface. If some implementation decides to use function overloading, it might declare a constructor with just a single parameter (size) in std::vector. This does not affect the end result though: all vector elements should begin their lives as if they were value-initialized.

这篇关于未初始化向量中的元素值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆