Foo &foo = Bar() 是合法的还是编译器问题
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
临时对象不绑定到非常量引用。这就是语言的设计方式。
虽然原则上不存在允许非恒定访问临时对象的技术障碍,但这几乎总是糟糕的设计,而且常常是彻头彻尾的逻辑错误,因此标准不允许这样做。如果您觉得需要修改临时项,您应该重新考虑为什么要这样做。
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.
您正在为引用分配一个临时值。它是临时的,因为在这里,
Bar()
的作用类似于一个返回Bar
实例的函数,该实例将在表达式范围的 和 处消失,即此处的末尾线。这是非常危险和非法的,因为取消引用foo
会产生未定义的行为。我不知道为什么 MSVC++ 允许这个“功能”,这一定是一个严重的错误。使用警告级别 4 (/W4),您将得到
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 aBar
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 thefoo
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
You should always write code with warning level 4.
Lastly, @KerrekSB's answer is better than mine, you should choose his' as an answer.