为什么编译器会允许 Initializing a Class with reference member by default constructor

why would complier allow Initializing a Class with reference member by default constructor

我正在学习 C++ primer 5th,并且知道当 class 定义引用成员时需要构造函数初始值设定项,否则编译器会抱怨它。

但是,我写了一个静态工厂方法,用空语句返回 class。

#include <iostream>

using namespace std;

//Learning default initializing values.
class Default {
   public:
    Default(int t) : r(t) {}
    static Default FromDefault() {}

    friend ostream& operator<<(ostream& os, const Default& d) {
        os << "c " << d.c << endl
           << "a " << d.a << endl
           << "b " << d.b << endl
           << "d " << d.d << endl
           << "l " << d.l << endl;
        return os;
    }

   private:
    int& r;  //a reference which require to be initialized
    char c;
    int a;
    float b;
    double d;
    long l;
};

int main() {
    cout << Default::FromDefault();
    return 0;
}

我以为代码不会通过编译器,但它确实通过了。只要我不使用成员r,就不会出现错误。

似乎引用 class 成员未能初始化,我只是想知道为什么编译器不会发现这个错误!

FromDefault 表现出未定义的行为,即在没有遇到 return 语句的情况下到达右大括号。


在一个不相关的注释中,Default(int t) 构造函数将引用 r 绑定到局部变量。一旦构造函数 returns、t 被销毁并且 r 变为悬空。之后任何尝试使用它都会表现出未定义的行为。