简体   繁体   English

在类的初始化和初始化列表中

[英]In class initialization and initializer list

I have recently discovered that you cant have at the same time in class initialization and initializer list. 我最近发现,您不能同时拥有类初始化和初始化列表。 The following code fails : 以下代码失败:

struct s
{
    int i=0;    
};
int main() {
    s s1; //s1.i = 0
    //s s2={42}; //fails
    return 0;
}

If I remove the in class initialization, the initializer list works fine ! 如果删除类中的初始化,则初始化器列表可以正常工作!

Can someone explains me why a such thing is no allowed ? 有人可以向我解释为什么不允许这种事情吗?

In fact this is allowed in C++14. 实际上,这在C ++ 14中是允许的。

struct s
{
    int i=0;    
};

int main() {
    s s1;
    s s2 = {42}; // succeeds
}

It's likely that your compiler just isn't implementing the new rule in C++14. 您的编译器可能没有在C ++ 14中实现新规则。 The latest version of clang, however, accepts this and does the correct thing in C++14 mode. 但是,最新版本的clang接受了这一点,并在C ++ 14模式下执行了正确的操作。

When in-class initialization was added to C++11 it was specified such that it prevented a class from being an aggregate. 当将类内初始化添加到C ++ 11时,它被指定为防止类成为聚合。 This was done because at the time the aggregate concept was closely related to PoD types which need to be trivially constructible. 这样做是因为当时聚合概念与PoD类型密切相关,而PoD类型则需要简单地构造。 Having an in-class initialization means that a type is no longer trivially constructible. 具有类内初始化意味着类型不再是普通可构造的。 Since then, however, the two concepts have become more independent, and so for C++14 a short proposal reversing that decision was accepted. 但是从那时起,这两个概念变得更加独立,因此对于C ++ 14来说,一个简短的提议可以扭转该决定,因此被接受。

This initialization: 此初始化:

s s1 = { 42 };

requires that s be an aggregate , or that it have a valid constructor taking eg an int or an std::initializer_list . 要求s是一个集合 ,或者它具有一个有效的构造函数,该构造函数采用int或std::initializer_list

When you add a member initialization at the point of declaration, you render your class s a non-aggregate, so you can no longer use aggregate initialization. 当你在声明中对添加成员初始化,您呈现类s一个非集合,这样你就可以不再使用集合初始化。

You could use the same initialization syntax for your non-aggregate by adding a constructor: 通过添加构造函数,可以对非聚合使用相同的初始化语法

struct s
{
    s(int i) : i(i) {}
    int i=0;    
};

I believe this restriction has been relaxed for C++14. 我相信对于C ++ 14,此限制已经放宽了。

See What are aggregates... for more information. 有关更多信息,请参见什么是聚合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM