C++初始化列表和默认值

Jos*_*osé 6 c++ g++ c++14

这段代码对C++ 14有效吗?

using namespace std;
struct Point
{
  int x = 0;
  int y = 0;
};
Point p2 {1, 1};
Run Code Online (Sandbox Code Playgroud)

它使用clang ++ 7.0编译得很好,在两种情况下它都不适用于G ++ 4.9我将--std = c ++ 1y传递给编译器.

在G ++中,当我从结构定义中删除默认值时,它可以工作.

g++ test_constexpr_ctor.cc --std=c++1y -o test
test_constexpr_ctor.cc:7:15: error: no matching function for call to ‘Point::Point(<brace-enclosed initializer list>)’
Point p2 {1, 1};
            ^
test_constexpr_ctor.cc:7:15: note: candidates are:
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point()
struct Point
        ^
test_constexpr_ctor.cc:1:8: note:   candidate expects 0 arguments, 2 provided
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(const Point&)
test_constexpr_ctor.cc:1:8: note:   candidate expects 1 argument, 2 provided
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(Point&&)
test_constexpr_ctor.cc:1:8: note:   candidate expects 1 argument, 2 provided
Run Code Online (Sandbox Code Playgroud)

Sin*_*all 3

该代码有效。

\n\n
    \n
  1. (8.5.4/3):
  2. \n
\n\n
\n

类型\n T\n 的对象或引用的列表初始化定义如下:\n \xe2\x80\x94\n 如果\n T\n 是聚合,则执行聚合初始化

\n
\n\n
    \n
  1. c++14 中的聚合定义为 (8.5.1/1):
  2. \n
\n\n
\n

聚合是一个数组或类(子句 9 ),没有用户提供的构造函数(子句 12.1 ),没有私有或受保护的非静态数据成员(子句 11 \n ),没有基类(子句\n 10\n ),并且没有虚函数(\n 10.3\n )。

\n
\n\n

请注意,在 c++11 中,这个定义看起来有所不同(强调我的):

\n\n
\n

\n 聚合\n 是一个数组或类(子句\n 9\n ),没有用户提供的构造函数(\n 12.1\n ),没有\n 大括号或等于\n 初始化器\n 对于非- 静态数据成员 (\n 9.2\n ),没有私有或受保护的非静态数据成员 (条款\n 11\n ),\n 没有基类 (条款\n 10\n ),并且没有虚函数 (\ n 10.3\n )。

\n
\n\n

由于这部分在 c++14 中被删除,因此您的结构肯定是一个聚合,因此应该执行聚合初始化。

\n\n

这在 gcc5 中已修复(在更改列表中搜索“具有非静态数据成员初始值设定项的聚合”)。不过,我不会称其为“bug”,而是 gcc 团队仅在 gcc 5.1.0 中实现了该更改。

\n