In place member initialization and aggregate initialization

和自甴很熟 提交于 2020-01-13 19:45:05

问题


I have this simple struct and a function taking it:

struct S
{
    int a;
};

void foo(S){}

foo({5});

This works fine.

But if I change int a; to int a{0}; VisualStudio (2013 and 2015) complains:

error C2664: 'void foo(S)': cannot convert argument 1 from 'initializer list' to 'S'

I can't find corresponding rule for this in the documentation. But both gcc and clang accept this without problem.


回答1:


struct S
{
    int a;
};

is an aggregate whereas

struct S
{
    int a {0}; // or int a = 0;
};

is not an aggregate in c++11, but is in c++14.

VisualStudio (2013 and 2015) still uses the c++11 rules in this regard.

foo({5}); is valid for aggregate. For non aggregate, it will (try to) call appropriate constructor, but S doesn't have one valid for this argument.



来源:https://stackoverflow.com/questions/35769246/in-place-member-initialization-and-aggregate-initialization

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