C++ 编译器警告 - 返回局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1303947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ compiler warning - returning local variable
提问by trikker
I'm simply trying to overload a + operator and I'm getting this compiler warning
我只是想重载 + 运算符,但收到此编译器警告
reference to local variable 'tmp' returned
Here is the code for the overload
这是重载的代码
const Int& Int::operator+(const Int& p) const
{
Int tmp = value + p.value;
return tmp;
}
Here is the class
这是课堂
class Int{
int value;
public:
Int() {} // default constructor
Int(int v) : value(v) {}
Int& operator=(const Int&);
const Int& operator+(const Int&) const;
};
回答by Sahas
You can't return a reference to a local variable. Inside the operator+()
function, you're creating a local variable called tmp
. It will get destroyed as soon as the function exits. You can't return a reference to that variable, because it no longer exists when the calling function gets the return value.
您不能返回对局部变量的引用。在operator+()
函数内部,您正在创建一个名为 的局部变量tmp
。一旦函数退出,它就会被销毁。您不能返回对该变量的引用,因为当调用函数获得返回值时它不再存在。
Change your definition of the function to:
将函数的定义更改为:
const Int operator+(const Int&) const;
It would build without warnings and work fine too.
它会在没有警告的情况下构建并且也能正常工作。
回答by Peter Smit
What you try to do is to return a reference to a memory location that will be invalid the moment you return it.
您尝试做的是返回对内存位置的引用,该引用在您返回时将无效。
The variable tmp will disappear when it goes out of scope (that is, when operator+ is finished).
当变量 tmp 超出范围时(也就是当 operator+ 结束时),它就会消失。
Because your return type is Int&, not the value of tmp is returned at "return tmp" but a reference to tmp. This is not correct because tmp will not exist anymore after the method is finished!!
因为您的返回类型是 Int&,所以在“return tmp”处返回的不是 tmp 的值,而是对 tmp 的引用。这是不正确的,因为方法完成后tmp将不再存在!!
Solution: Do not return as reference, but as Int
解决方案:不要作为引用返回,而是作为 Int
回答by thomasalvatran
tmp
has a storage class of auto
and will disappear when we exit. The answer is to specify static.
tmp
有一个存储类auto
并且会在我们退出时消失。答案是指定静态。
static Int tmp = value + p.value;
The storage assigned to tmp
will remain reserved for the duration of the program.
分配给的存储空间tmp
将在程序运行期间保留。