c++ - gcc:缺少有关构造函数中初始化顺序的警告

标签 c++ gcc initialization initializer-list

gcc 是否应该警告 C 类中成员变量 ab 的初始化顺序?基本上对象 b 被初始化,它的构造函数在对象 A 之前被调用。这意味着 b 使用未初始化的 a

#include <iostream>

using namespace std;

class A
{
    private:
        int x;
    public:
        A() : x(10) { cout << __func__ << endl; }
        friend class B;
};

class B
{
    public:
        B(const A& a) { cout << "B: a.x = " << a.x << endl; }
};

class C
{
    private:
        //Note that because b is declared before a it is initialized before a
        //which means b's constructor is executed before a.
        B b;
        A a;

    public:
        C() : b(a) { cout << __func__ << endl; }
};

int main(int argc, char* argv[])
{
    C c;
}

gcc 的输出:

$ g++ -Wall -c ConsInit.cpp 
$ 

最佳答案

为了使其成为初始化顺序问题,您需要实际尝试以错误的顺序初始化子对象:

public:
    C() : a(), b(a) { cout << __func__ << endl; } 
          ^^^ this is attempted initialization out of order

如所写,唯一的违规行为是在之前将引用(B::B(const A&) 的参数)绑定(bind)到对象 (C::a)它的生命周期开始了,这是一个非常值得怀疑的违规行为,因为在 $3.8[basic.life]/5 以下,将指针指向 a 实际上是合法的(并且在 a 的初始化之前取消引用它是 UB)

关于c++ - gcc:缺少有关构造函数中初始化顺序的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10404889/

相关文章:

c# - Math.Random 算法

linux - __attribute__ ((weak)) 不适用于全局变量

JavaScript - 使用数据创建数组而不循环

rust - 写入 MaybeUninit 结构中的字段?

c++ - 如何遍历 vector 中的 vector ?

c++ - 奇怪的 C++ 字符串连接行为

c++ - 将一对成员分配给变量

c - C 中的 Posix 正则表达式

c++11随机数生成: how to re-implement `uniform_int_distribution` with `mt19937` without templates

C++零初始化 - 为什么这个程序中的 `b`未初始化,但 `a`已初始化?