Search code examples
c++effective-c++

Returning local variables in C++ (Rule 21 in Effective C++, 3rd edition)


As known, returning local variable from function in C++, is unsafe, due to scoping. In Effective C++ Third Edition, Scott Meyers tells about this problem in item 21, at page 101. However, in conclusion he said, that right decision will be to write:

inline const Rational operator*(const Rational& lhs, const Rational& rhs) {
    return Rational(lhs.n * rhs.h, lhs.d * rhs.d);
}

Isn't this also a bad practice, and this function is unsafe?


Solution

  • You can't actually return a local variable. You can return the value of a local variable, or a pointer to it (i.e., its address), or a reference to it.

    Returning the value of a local variable is perfectly safe:

    int good_func() {
        int local = 42;
        return local; // returns a copy of the value of "local"
    }
    

    Returning a pointer or reference to a local variable is unsafe, because the variable ceases to exist when the function terminates:

    int* bad_func() {
        int local = 42;
        return &local; // returns a pointer to "local"
    }
    

    (The same applies in C, except that C doesn't have C++-style references.)