【问题标题】:why would complier allow Initializing a Class with reference member by default constructor为什么编译器允许默认构造函数使用引用成员初始化类
【发布时间】:2020-08-17 12:23:21
【问题描述】:

我正在学习 C++ 入门 5,并且知道当类定义引用成员时需要构造函数初始化器,否则编译器会抱怨它。

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

#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,就不会出现错误。

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

【问题讨论】:

  • 我认为代码不会通过编译器,但它确实通过了 -- 您是否看到编译器警告FromDefault() 没有在应该返回值时返回?
  • 是的,我看到了警告。我只是以为编译器会生成一个默认返回值。
  • @JackLi 是什么给了你这个想法?
  • @RemyLebeau 我从输出中推断出来。 (我不知道为什么编译器允许这种编码,因为 go 对它很严格)

标签: c++ class reference default


【解决方案1】:

FromDefault 表现出未定义的行为,通过到达右大括号而不遇到return 语句。


另外,Default(int t) 构造函数将引用 r 绑定到局部变量。一旦构造函数返回,t 就被销毁,r 变得悬空。之后任何尝试使用它都会表现出未定义的行为。

【讨论】:

    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2020-05-26
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多