Search code examples
c++lvalue

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


In below code, compiler warns about returning reference to local when bar() method is called. I was expecting similar warning about foo() method as well.

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

Output of compilation:

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

Solution

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

    Because compilers are not perfect and ultimately it is your responsibility to not write invalid code. The compiler is not obligated to warn on everything that is wrong (in fact, it's obligated to warn on very little, but most try to do better than the minimal requirement).