Foo &foo = Bar() 是合法的还是编译器问题

发布于 2024-12-13 01:51:47 字数 283 浏览 0 评论 0原文

struct Foo {};
struct Bar : Foo {};

Foo &foo = Bar(); // without const

正如这个问题的答案和评论中所写的那样,我无法将右值分配给引用。但是,我可以编译此代码(MSVC++ 2010),而不会出现错误或警告。这是我的编译器的已知问题吗?

struct Foo {};
struct Bar : Foo {};

Foo &foo = Bar(); // without const

As it is written in the answers and comments to this question, I cannot assign a rvalue to a reference. However, I can compile this code (MSVC++ 2010) without error or warning. Is it a known problem of my compiler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

夏了南城 2024-12-20 01:51:47

临时对象不绑定到非常量引用。这就是语言的设计方式。

虽然原则上不存在允许非恒定访问临时对象的技术障碍,但这几乎总是糟糕的设计,而且常常是彻头彻尾的逻辑错误,因此标准不允许这样做。如果您觉得需要修改临时项,您应该重新考虑为什么要这样做。

Temporaries do not bind to non-constant references. That's just the way the language is designed.

While there's in principle no technical obstruction to permitting non-constant access to temporaries, that would almost always be poor design, and quite often flat-out logically erroneous, so the standard just doesn't allow it. If you feel the need to modify a temporary, you should rethink why you want to do that.

深海不蓝 2024-12-20 01:51:47

您正在为引用分配一个临时值。它是临时的,因为在这里,Bar() 的作用类似于一个返回 Bar 实例的函数,该实例将在表达式范围的 和 处消失,即此处的末尾线。这是非常危险和非法的,因为取消引用 foo 会产生未定义的行为。我不知道为什么 MSVC++ 允许这个“功能”,这一定是一个严重的错误。

使用警告级别 4 (/W4),您将得到

warning C4239: nonstandard extension used : 'initializing' : conversion from 'Bar' to 'Bar &'

You should always write code with warning level 4.
最后,@KerrekSB 的答案比我的好,你应该选择他的答案。

You are assigning a temporary value to the reference. It is temporary because, here, Bar() acts like a function that returns a Bar instance which will evaporate at the and of the expression scope, which is here the end of line. It is highly dangerous and illegal, because dereferencing the foo creates an undefined behaviour. I have no idea why MSVC++ allows this "feature" which must be a solid error.

With warning level 4 (/W4) you will get

warning C4239: nonstandard extension used : 'initializing' : conversion from 'Bar' to 'Bar &'

You should always write code with warning level 4.
Lastly, @KerrekSB's answer is better than mine, you should choose his' as an answer.

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