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

那年仲夏 提交于 2019-12-11 16:23:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!