本文介绍了等号对大括号初始化有影响吗?例如.'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 }; 样式之间的变量,我发现区别在于次要的,最坏的情况只会导致关于滥用显式构造函数的有用编译器消息.

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

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

这篇关于等号对大括号初始化有影响吗?例如.'T a = {}' 与'T a{}'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 10:28