![](/img/trans.png)
[英]Why doesn't the compiler warn “returning address of local variable or temporary” when returning a local reference to a local variable?
[英]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++ 編譯器不警告返回對局部變量的引用?”
因為編譯器並不完美,最終不編寫無效代碼是您的責任。 編譯器沒有義務對所有錯誤發出警告(實際上,它有義務警告很少的,但大多數嘗試做得比最低要求更好)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.