Codepad.org C++代码给出了错误的结果
只是一个小问题:
您能告诉我此代码中存在什么问题吗?它应该打印出 9
但它确实是 4.8921e-270
,但是,当取消注释第 4 行时,它也可以正常工作。
我不明白这里可能出了什么问题。谢谢 !
代码:
double& foo() {
double x = 9;
double &y = x;
//cout << y << "\n";
return y;
}
int main() {
cout << foo() << "\n";
}
结果: 4.8921e-270
Just a tiny question:
Can you tell me what's the issue here in this code ? It should print out 9
but it does 4.8921e-270
, however, when uncommenting line 4, it works just fine, too.
I don't understand what might be wrong here. Thank you !
Code:
double& foo() {
double x = 9;
double &y = x;
//cout << y << "\n";
return y;
}
int main() {
cout << foo() << "\n";
}
Result:4.8921e-270
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
返回堆栈上对象的引用/指针是一个坏主意。当您离开该功能时,它们可能会被破坏。尝试按值返回它:
现在返回值被复制,而不是对可能不再存在的对象的引用。
It is a bad idea to return references/pointers to objects on the stack. They are likely destroyed when you leave the function. Try returning it as per value:
Now the return value is copied instead of a reference to an object that is probably not existing anymore.
您正在返回对本地对象的引用,当
foo
完成时,该对象将不再存在,然后当您取消引用它时,您会得到未定义的行为。You are returning a reference to a local object, the object ceases to exist when
foo
completes, and then you get Undefined Behavior when you dereference it.返回对堆栈上对象的引用绝不是一个好主意。当您离开该功能时,它们很可能会消失。您可以尝试按值返回它。
Never a good idea to return references to objects on stack. Most likely they would be disappear when you leave the function. You might try returning it as per value.
您返回对局部变量的引用 - 因为局部变量一旦 foo() 返回就超出范围,该值不再存在。
因此,您应该将返回类型更改为 double (强烈推荐)并返回 x 或(如果您绝对想要/必须返回引用)使用静态变量:
You return a reference to a local variable - since the local variable goes out of scope as soon as foo() returns, the value no longer exists.
So you should either just change the return type to double (highly recommended) and return x or (if you absolutely want/have to return a reference) use a static variable instead:
我经常通过 const ref 返回类的数据成员:
那么只要您的 Foo 实例在范围内(您不想返回对局部变量的引用),那么使用 getBT() 之一应该是安全的高效的。
I often return data members of a class by const ref:
Then as long as your instance of Foo is in scope (you don't want to return a ref to a local variable) then using one of the getBT() should be safe and efficient.