为什么 C++ 编译器不警告返回对局部变量的引用

Why does c++ compiler not warn about returning reference to local variable?

本文关键字:局部变量 引用 返回 警告 C++ 编译器 为什么      更新时间:2023-10-16

在下面的代码中,编译器警告在调用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++ 编译器不警告返回对局部变量的引用?">

因为编译器并不完美,最终你有责任不编写无效的代码。编译器没有义务警告所有错误(事实上,它有义务警告很少,但大多数人都试图做得比最低要求更好(。