等号是否在大括号初始化中有所不同? [英] Does the equals sign make a difference in brace initialization?

查看:200
本文介绍了等号是否在大括号初始化中有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我测试了这两个在我能想到的情况,我没有注意到一个区别。 此回答表明两者之间存在细微差别:



<对于变量,我不太注意 T t = {init}; T t { init}; styles,我发现它的区别是小的,并且在最坏的情况下,只会导致一个有用的编译器消息,关于一个显式的构造函数。


$ b

解决方案

我知道的唯一重大差异是在处理显式构造函数:

  struct foo 
{
explicit foo(int);
};

foo f0 {42}; // OK
foo f1 = {42}; //不允许

这与传统初始化类似:

  foo f0(42); // OK 
foo f1 = 42; //不允许

请参阅[over.match.list] / 1。






除此之外,还有一个缺陷(请参阅 T a = {something} CWG 1270 ) >

  struct aggr 
{
int arr [5];
};

aggr a0 = {1,2,3,4,5}; // OK
aggr a1 {1,2,3,4,5}; //不允许


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:

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 these two?

解决方案

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

See [over.match.list]/1.


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

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

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