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

时间:2019-03-23 14:32:43

标签: c++ lvalue

在下面的代码中,编译器警告在调用bar()方法时返回对本地的引用。我也期待关于foo()方法的类似警告。

1.0

编译输出:

#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;
}

1 个答案:

答案 0 :(得分:4)

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

因为编译器并不完美,最终,不编写无效代码是您的责任。编译器没有义务对所有错误消息进行警告(实际上,它有义务警告很少,但大多数人试图做得比最低要求还要好)。