[英]Initialize a std::vector of structures to zero
I am guaranteed to initialize a vector of struct with each element initialized to zero with that code?我保证用该代码初始化一个结构向量,每个元素都初始化为零?
#include <vector>
struct A {
int a, b;
float f;
};
int main()
{
// 100 A's initialized to zero (a=0, b=0, f=0.0)
// std::vector<A> my_vector(100, {}); does not compile
std::vector<A> my_vector(100, A{});
}
Short answer: Yes简短的回答:是的
To know how refer below: when you write要知道如何参考下面:当你写
std::vector<A> my_vector(...)
you are doing value initialization if the parentheses are empty, or direct initialization if non-empty.如果括号为空,则进行 值初始化,如果括号非空,则进行直接初始化。
and when you write A{} you are doing list initialization which implies value initialization if the braces are empty, or aggregate initialization if the initialized object is an aggregate.并且当您编写 A{} 时,您正在执行 列表初始化,如果大括号为空,则意味着值初始化,或者如果初始化的 object 是聚合,则表示聚合初始化。
as your parentheses are non-empty so below code因为你的括号是非空的所以下面的代码
std::vector<A> my_vector(100, A{});
is interpreted as被解释为
std::vector<A> my_vector(/*created vector of 100 elements */ 100, /* by list Initialization of struct with default values*/A{});
As A{} is empty in this case you are doing value initialization which is leading to zero_initialization as由于 A{} 在这种情况下为空,因此您正在进行值初始化,这将导致zero_initialization为
- As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.
作为非类类型和没有构造函数的值初始化 class 类型的成员的值初始化序列的一部分,包括未提供初始化器的聚合元素的值初始化。
Yes it is guaranteed since A{}
isvalue initialization and from cppreference :是的,因为
A{}
是值初始化并且来自cppreference ,所以可以保证:
Zero initialization is performed in the following situations:
在以下情况下执行零初始化:
- As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.
作为非类类型和没有构造函数的值初始化 class 类型的成员的值初始化序列的一部分,包括未提供初始化器的聚合元素的值初始化。
You can also use:您还可以使用:
std::vector<A> my_vector(100, {0,0,0});
Yes, you are guaranteed to have zero initialization with that code是的,您可以保证使用该代码进行零初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.