标签: c++ reference constructor scope
以下代码是否安全?
class B { public: int& b; B (int& _b) : b(_b) {} }; B* foo() { int a; return new B(a); }
foo返回的对象中的引用是否会指向任何内容(因为int a超出范围)或者编译是否计算出来了?
答案 0 :(得分:5)
编译器可能会警告您,但新创建的对象肯定包含悬空的无效引用,因为对象a在foo范围的末尾停止存在。
a
foo