如果我有一个通用的 linux 结构,例如:
struct sockaddr_in
{
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
unsigned char __pad[__SOCK_SIZE__ - sizeof(short int)
- sizeof(unsigned short int) - sizeof(struct in_addr)];
};
#define sin_zero __pad
然后我执行聚合初始化:
struct sockaddr_in my_addr = { 0 };
为什么这会将每个成员都初始化为 0?
我的意思是:文档说:
If the number of initializer clauses is less than the number of members or initializer clauses is completely empty, the remaining members are initialized by their brace-or-equal initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, which performs value-initialization.
为简单起见:为什么这段代码会打印 0?
struct sockaddr_in my_addr = {2, 2}; // initialize sin_family and sin_port to 2, everything else value-initialized
my_addr = {0};
std::cout << my_addr.sin_port; // Why is this 0?
最佳答案
这包含在 draft C++14 standard 中8.5.4
List-initialization 部分说:
List-initialization of an object or reference of type T is defined as follows:
并包括:
If T is an aggregate, aggregate initialization is performed (8.5.1).
并有以下示例:
struct S2 {
int m1;
double m2, m3;
}
S2 s21 = { 1, 2, 3.0 }; // OK
S2 s22 { 1.0, 2, 3 }; // error: narrowing
S2 s23 { }; // OK: default to 0,0,0
和 8.5.1
聚合说:
If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equalinitializer, from an empty initializer list (8.5.4). [ Example:
struct S { int a; const char* b; int c; int d = b[a]; }; S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", ss.c with the value of an expression of the form int{} (that is, 0)
请注意 8.5.4
在 C++11 中略有不同,它说:
List-initialization of an object or reference of type T is defined as follows:
If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
Otherwise, if T is an aggregate, aggregate initialization is performed (8.5.1).
关于c++ - 用 less 子句结构聚合初始化,为什么它初始化所有东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26256174/