如果初始化列表顺序与类中的变量顺序不匹配,为什么gcc会抛出一个合适的东西呢?
class myClass
{
public:
int A;
int B;
myClass();
};
myClass::myClass() :
B(1),
A(2)
{}
Run Code Online (Sandbox Code Playgroud)
将导致:
file.h:274: warning: 'myClass::A' will be initialized after
file.h:273: warning: 'int myClass::B
file.cpp:581: warning: when initialized here
Run Code Online (Sandbox Code Playgroud)
发出这种警告有什么具体原因吗?是否存在与初始化类变量相关的风险,其顺序与在类中定义的顺序不同?
(注意,有一个问题触及了这个主题,但答案几乎是"因为它应该是这样"而没有给出任何理由,为什么应该订购,或者这有什么不对的故障 - 我会想知道为什么存在这样的限制 - 有人会举例说明它可能适得其反吗?)
受到我(目前已删除)对这个问题的回答的启发(但我的评论中有一个摘要),我想知道Derived下面代码中类的构造函数是否表现出未定义的行为。
#include <iostream>
class Base {
public:
Base(int test) {
std::cout << "Base constructor, test: " << test << std::endl;
}
};
class Derived : public Base {
private:
int variable;
public: Derived() : Base(variable = 50) { // Is this undefined behaviour?
}
};
int main()
{
Derived derived;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道,当基 c'tor 被调用时,派生对象尚未(正式)构造,因此variable成员的生命周期尚未开始。但是,C++ 标准的摘录(感谢NathanOliver提供参考)表明(可能)该对象可以“以有限的方式”使用(粗体我的):
7 同样,在对象的生命周期开始之前 但在对象将占用的存储空间已经分配之后,或者在对象的生命周期结束之后并且在对象占用的存储空间被重用或释放之前,任何引用可以使用原始对象,但只能以有限的方式使用。对于正在构建或销毁的对象,请参阅 [class.cdtor]。否则,这种泛左值指的是分配的存储([basic.stc.dynamic.allocation]),并且使用不依赖于其值的泛左值的属性是明确定义的。…
显然,如果variable一个对象本身有一个非平凡的构造函数,那么(几乎可以肯定)这里会有未定义的行为。但是,对于像 an …