这是否会导致引用在超出范围后不指向任何内容

Will this cause a reference to point to nothing after it goes out of scope?

本文关键字:范围 任何内 是否 引用      更新时间:2023-10-16

以下代码安全吗?

class B {
  public:
    int& b;
    B (int& _b) :
      b(_b) {}
};
B* foo() {
  int a;
  return new B(a);
}

foo返回的对象中的引用是否指向任何内容(因为int a超出了范围)还是编译解决了这个问题?

编译器可能会警告您,但新创建的对象肯定包含一个悬而未决的无效引用,因为该对象a停止存在于foo范围的末尾。