等号对大括号初始化有影响吗?例如.'T a = {}' 与'T a{}'

在C++11中有两种初始化变量的方法:

Here are two ways to initialize a variable in C++11:

T a {something};
T a = {something};

我在我能想到的所有场景中都测试了这两个,但我没有注意到其中的差异.这个答案表明两者之间存在细微差别:

I tested these two in all scenarios I could think of and I failed to notice a difference. This answer suggests that there is a subtle difference between the two:

对于我不太注意 T t = { init };T t { init }; 样式之间的变量,我发现区别在于次要的,最坏的情况只会导致关于滥用显式构造函数的有用编译器消息.

For variables I don't pay much attention between the T t = { init }; or T t { init }; styles, I find the difference to be minor and will at worst only result in a helpful compiler message about misusing an explicit constructor.

那么,这两者有什么区别吗?

So, is there any difference between the two?

推荐答案

我所知道的唯一显着区别在于 explicit 构造函数的处理方式:

The only significant difference I know is in the treatment of explicit constructors:

struct foo
{
    explicit foo(int);
};

foo f0 {42};    // OK
foo f1 = {42};  // not allowed

这类似于传统"初始化:

This is similar to the "traditional" initialization:

foo f0 (42);  // OK
foo f1 = 42;  // not allowed

参见 [over.match.list]/1.

See [over.match.list]/1.

除此之外,还有一个缺陷(参见 CWG 1270) 在 C++11 中只允许 T a = {something}

Apart from that, there's a defect (see CWG 1270) in C++11 that allows brace-elision only for the form T a = {something}

struct aggr
{
    int arr[5];
};

aggr a0 = {1,2,3,4,5};  // OK
aggr a1 {1,2,3,4,5};    // not allowed

相关文章