问题
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?
UPD: Thanks everybody for explanation.
回答1:
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.)
回答2:
Returning local variable from a function is normal and nothing wrong. Returning pointer or reference to a local variable is different story, but in your example there is nothing of the sort.
回答3:
No, this is not unsafe, because Rational
is returned by value. This means that the caller gets a copy of the Rational
that you create, which makes the whole process safe.
It is unsafe to return a reference to a local variable, or to access through a reference an object that has gone out of scope. This is not what is happening in the code example, though.
Note that the copy may be created without copying, which has a potential of degrading performance. This is because C++ compilers can use return value optimization technique described here.
回答4:
No it's not unsafe, you are returning by value, even in C++98 it's safe, but in C++98 possibly will no be fast enough because of the additional unnecessary copy (using Move Semantic in C++11 avoid the copy). Nevertheless it's not recommended for big object by many of the C++ gurus. The problem with big objects is that move might decay into copy in some of the data members of the object.
来源:https://stackoverflow.com/questions/24789982/returning-local-variables-in-c-rule-21-in-effective-c-3rd-edition