括号初始化中的等号是否有所不同?例如. 'T a = {}'与'T a {}' [英] Does the equal sign make a difference in brace initialization? eg. 'T a = {}' vs 'T a{}'

查看:127
本文介绍了括号初始化中的等号是否有所不同?例如. '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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆