为什么 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
"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
"Why does c++ compiler not warn about returning reference to local variable?"
因为编译器并不完美,最终您有责任不编写无效代码。编译器没有义务对所有错误发出警告(事实上,它有义务警告非常少,但大多数尝试做得比最低要求更好)。