具有非静态成员初始值设定项的类的 C++11 聚合初始化

标签 c++ c++11 gcc c++14 aggregate-initialization

标准是否允许:

struct A
{
  int a = 3;
  int b = 3;
};

A a{0,1}; // ???

这个类还是聚合的吗? clang 接受此代码,但 gcc 不接受。

最佳答案

在 C++11 中,具有类内成员初始值设定项使得结构/类不是聚合 — 然而,这在 C++14 中发生了变化。当我第一次遇到它时,我感到很惊讶,这个限制的理由是类内初始化器与用户定义的构造器非常相似,但反论点是没有人真的期望添加类内初始化器应该他们的类/结构是非聚合的,我肯定没有。

来自draft C++11 standard 8.5.1 聚合部分(强调我的前进):

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

C++14 中同段内容如下:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

此更改包含在 N3605: Member initializers and aggregates 中其中有以下摘要:

Bjarne Stroustrup and Richard Smith raised an issue about aggregate initialization and member-initializers not working together. This paper proposes to fix the issue by adopting Smith's proposed wording that removes a restriction that aggregates can't have member-initializers.

这条评论基本上总结了不愿让它们成为聚合体的情况:

Aggregates cannot have user-defined constructors and member-initializers are essentially some kind of user-defined constructor (element) (see also Core Defect 886). I'm not against this extension, but it also has implications on what our model of aggregates actually is. After acceptance of this extension I would like to know how to teach what an aggregate is.

修订版N3653May 2013 中被采用.

更新

emsr 指出 G++ 5.0 now supports C++14 aggregates with non-static data member initializers使用 std=c++1y-std=c++14:

struct A { int i, j = i; };
A a = { 42 }; // a.j is also 42

看到它工作 live .

关于具有非静态成员初始值设定项的类的 C++11 聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640295/

相关文章:

c++ - 匿名结构内部循环

c++ - `std::pmr::monotonic_buffer_resource` : why the `dynamic_cast` ?

c++ - 这个方法声明/定义是什么意思? (与传递数组有关?)

C++14 转换为成员函数的返回类型 - 简洁版本

c++ - 使用 For 循环和用户输入写入和读取数组

c++ - 在我的神经网络程序中使用的最有效的数据结构是什么?我的程序是否需要动态分配

c++ - 无效的操作数二进制表达式:ostream 和 std::u32string

c - 为什么会出现 C malloc 断言失败?

c++ - 从 C++ std::string& 获取 unichar * 以在 Objective-C++ 中创建非空 NSString

c++ - 适用于 C++ Windows 7 64 位 PC 的 Eclipse