使用 {} 初始化 class 个成员

Initializing class members with {}

有人给了我以下代码(部分):

struct MyStruct
{
    int x = {};
    int y = {};

};

我以前从未见过这种语法,用 {} 初始化是什么意思?

这是 default member initializer (C++11 起),

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

初始化本身是 copy-list-initialization (C++11 起),作为结果,数据成员 xy 将被值初始化(和零初始化作为内置类型)到 0.

自C++11标准以来,有两种初始化成员变量的方法:

  1. 使用构造函数初始化列表为"usual":

    struct Foo
    {
        int x;
    
        Foo()
            : x(0)
        {
        }
    };
    
  2. 使用新的 内联 初始化,其中成员使用正常的初始化语法获取 "default" 值:

    struct Foo
    {
        int x = 0;
    };
    

这两种方式都适用于许多等效的值和类型。