从函数中返回布尔文字作为参考

发布于 2025-01-18 07:03:53 字数 365 浏览 2 评论 0原文

我在尝试查找错误时遇到了此代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

星軌x 2025-01-25 07:03:53

这是未定义的行为,因为您试图返回一个值的引用,一旦退出该函数,该值的范围就会被破坏。

This is undefined behaviour as you are trying to return a reference on a value whose scope is destroyed once you exit the function.

时光匆匆的小流年 2025-01-25 07:03:53

您是否尝试过更改编译器版本?
该代码甚至不应该编译,因为它将引用与临时值的参考结合。低于G ++ 7.5的输出
G ++ 7.5.0

error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’

非常量参考不会与临时值结合。
汇编问题可以通过临时参考绕过,

const bool& foo() {
    return x == 10;
}

但是由于与临时值链接时,未定义的行为将保持不变。

**** 更新
正如建议的那样,我报告的答案是指一个初始问题,在该问题中,通过参考返回的函数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

error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’

A not const reference does not bind with temporary values.
The compilation problem can be bypassed with a temporary reference

const bool& foo() {
    return x == 10;
}

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

用心笑 2025-01-25 07:03:53

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文