从函数中返回布尔文字作为参考
我在尝试查找错误时遇到了此代码:
int x = 10; // for example
const bool& foo() {
return x == 10;
}
int bar() {
bool y = foo(); // error here
}
此代码块在使用 gcc11.2 编译时会导致崩溃,而它在 Visual Studio 2019 中正常工作并将 y 设置为 true。两个编译器都会发出有关返回对局部变量的引用的警告。我想知道这种行为是否属于UB。 (我们通过将 bool& 更改为 bool 来修复此错误)
编辑:我忘记将 const 放在 bool& 之前,对此感到抱歉。
I have encountered this code during trying to find a bug:
int x = 10; // for example
const bool& foo() {
return x == 10;
}
int bar() {
bool y = foo(); // error here
}
This code block causes a crash when compiled with gcc11.2, while it works correctly and sets y as true in Visual Studio 2019. Both compilers give a warning about returning reference to local variable. I would like to know whether this behaviour is an UB or not. (We fixed this bug by changing bool& to bool)
Edit: I forgot to put const before bool&, sorry about that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是未定义的行为,因为您试图返回一个值的引用,一旦退出该函数,该值的范围就会被破坏。
This is undefined behaviour as you are trying to return a reference on a value whose scope is destroyed once you exit the function.
您是否尝试过更改编译器版本?
该代码甚至不应该编译,因为它将引用与临时值的参考结合。低于G ++ 7.5的输出
G ++ 7.5.0
非常量参考不会与临时值结合。
汇编问题可以通过临时参考绕过,
但是由于与临时值链接时,未定义的行为将保持不变。
**** 更新
正如建议的那样,我报告的答案是指一个初始问题,在该问题中,通过参考返回的函数foo()现在已经对问题进行了编辑以整合问题。感谢Yunnosch的建议
Have you tried changing the compiler version?
The code shouldn't even compile because it binds a reference to a temporary value. Below output of g++ 7.5
g++ 7.5.0
A not const reference does not bind with temporary values.
The compilation problem can be bypassed with a temporary reference
but the undefined behavior would remain as it is linked to a temporary value.
**** Update
As suggested I report that the answer referred to an initial question in which the function foo () returned by reference not const Now the question has been edited to incorporate this. Thanks Yunnosch for the suggestion
x == 10
是右值而不是左值,它没有地址,您可以引用它。如果它在 VS 2019 下工作,则意味着编译器必须优化代码并内联函数或类似的东西。在调试模式下它不应该工作。x == 10
is a rvalue not an lvalue, it has not address and you can reference it. If it works under VS 2019 it means that the compiler must surely optimize the code and inline the function or something like that. In debug mode it should not work.