c++ - 用 less 子句结构聚合初始化,为什么它初始化所有东西?

标签 c++ initialization list-initialization

如果我有一个通用的 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 standard8.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/

相关文章:

c++ - 如何将函数静态应用于非类型模板包的各个元素并对结果求和?

C++ XML 到 C++ 对象映射库?

c++ - CATIA CAA编程介绍

c++ - 为什么引用某些导出的 const 变量的某些 const 变量会获得值 0?

c++ - 如何随机初始化常量数据成员?

c++ - 查找 C++ 静态初始化顺序问题

c++ - 为什么 braced-init-list 在函数调用和构造函数调用中的行为不同?

c++ - 我可以设置一个由 gdb 启动和附加的 linux 程序吗?

c++ - 为什么不能从初始化列表初始化我的类,即使它是从 std::list 派生的?

c++ - 启用默认初始化列表构造函数