c++ - 标准保证初始化顺序吗?

标签 c++

在下面的代码片段中,d1 的初始化器传递给尚未构造的 d2(正确吗?),所以 D 的复制构造函数中的 d.j 是未初始化的内存访问吗?

struct D
{
    int j;

    D(const D& d) { j = d.j; }
    D(int i) { j = i; }
};

struct A
{
    D d1, d2;
    A() : d2(2), d1(d2) {}
};

C++ 标准的哪一部分讨论了数据成员的初始化顺序?

最佳答案

我现在手边没有标准,所以我不能引用该部分,但是结构或类成员初始化总是按照声明的顺序进行。构造函数初始化列表中提及成员的顺序无关紧要。

Gcc 有一个警告 -Wreorder 当顺序不同时发出警告:

       -Wreorder (C++ only)
           Warn when the order of member initializers given in the code does
           not match the order in which they must be executed.  For instance:

                   struct A {
                     int i;
                     int j;
                     A(): j (0), i (1) { }
                   };

           The compiler will rearrange the member initializers for i and j to
           match the declaration order of the members, emitting a warning to
           that effect.  This warning is enabled by -Wall.

关于c++ - 标准保证初始化顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1774187/

相关文章:

c++ - 就快结束了! C++ 素数筛选套接字

c++ - 与结构数据赋值的不兼容类型(相同类型!)

c++ - lapacke 与 boost 冲突?

c++ - "expected primary expression __"是什么意思?

c++ - 使用 constexpr 数组作为模板非类型参数 (C++14)

c++ - 如果在结构内部使用 condition_variable 则不起作用

c++ - 带有模板参数或类型名的模板函数

c++ - 如何使用Cin第一次启用输入流?

c++ - Stringstream - 将对象转换为字符串

c++ - 这里的unique_ptr会不会有内存泄漏