Does the equal sign make a difference in brace initialization? eg. 'T a = {}' vs 'T a{}'

旧时模样 提交于 2020-01-19 07:31:18

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/20733360/does-the-equal-sign-make-a-difference-in-brace-initialization-eg-t-a-vs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!