为什么 C++ 编译器不警告返回对局部变量的引用
Why does c++ compiler not warn about returning reference to local variable?
在下面的代码中,编译器警告在调用bar((方法时返回对本地的引用。我也期待关于 foo(( 方法的类似警告。
#include <iostream>
class Value {
public:
int& foo() {
int tc = 10;
int& r_tc = tc;
return r_tc;
}
int& bar() {
int tc = 10;
return tc;
}
};
int main() {
Value value;
int& foo_ref = value.foo();
int& bar_ref = value.bar();
std::cout << foo_ref << std::endl;
return 0;
}
编译输出:
g++ -c refreturn.cc -g -std=c++1z; g++ -o refreturn refreturn.o
refreturn.cc: In member function ‘int& Value::bar()’:
refreturn.cc:12:13: warning: reference to local variable ‘tc’ returned [-Wreturn-local-addr]
int tc = 10;
^
Compilation finished at Sat Mar 23 07:29:31
"为什么 c++ 编译器不警告返回对局部变量的引用?">
因为编译器并不完美,最终你有责任不编写无效的代码。编译器没有义务警告所有错误(事实上,它有义务警告很少,但大多数人都试图做得比最低要求更好(。
相关文章:
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 返回对局部变量 - C++ 的引用
- 警告 C4101 未引用的局部变量
- 现代编译器会优化只引用对象子集的局部变量吗
- 右值引用和局部变量的移动
- 结构数组 - 未引用的局部变量
- 返回对局部变量的引用是否正常工作?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 三元运算符:编译器不发出局部变量警告的返回引用
- 为什么 C++ 编译器不警告返回对局部变量的引用
- 变量循环范围会导致返回局部变量的地址引用
- 通过引用返回局部变量
- 为什么我得到未引用的局部变量
- 返回由引用指定的引用局部变量
- 返回静态局部变量作为引用
- 没有返回对局部变量的引用的编译器警告
- 为什么在这段代码中返回对局部变量的引用
- 引用与设置局部变量
- 通过引用参数将局部变量分配给
- 捕获和调试对移动lambda内部局部变量引用的无效使用