绑定到临时的 Visual Studio 错误的非常量引用?

Non-const reference bound to temporary, Visual Studio bug?(绑定到临时的 Visual Studio 错误的非常量引用?)
本文介绍了绑定到临时的 Visual Studio 错误的非常量引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 gcc 中编译一些可移植代码时遇到了这个问题.基本上这个奇怪的代码在 Visual Studio 中编译,这真的让我大吃一惊:

I ran into this while compiling some portable code in gcc. Basically this strange code compiles in Visual studio which really just blows my mind:

class Zebra {int x;};
Zebra goo() {Zebra z; return z;}
void foo(Zebra &x)
{
    Zebra y;
    x = y;
    foo(goo());
}

Visual Studio 让这个飞起来.gcc 会将其作为编译错误捕获.有趣的是,如果您将 Zebra 类型定义为 int,VC++ 会抱怨.相当矛盾的行为.想法?

Visual studio lets this one fly. gcc will catch this as a compile error. Interestingly, If you typedef Zebra to int, VC++ will complain. Quite contradictory behavior. Thoughts?

推荐答案

这是 Visual Studio 的旧扩展,我在 Microsoft 站点上找到的唯一参考是此错误报告:Temporary Objects Can be Bound to Non-Const References,其中有以下示例代码:

This is old extension to Visual Studio, the only reference I could find on the Microsoft site was this bug report: Temporary Objects Can be Bound to Non-Const References, which has the following example code:

struct A {};

A     f1();
void f2(A&);

int main()
{
    f2(f1()); // This line SHALL trigger an error, but it can be compiled without any     errors or warnings.
}

其中一个回复指出:

有一个 4 级警告(如果您将/W4 传递给编译器,则启用 4 级警告)

There is a level 4 warning (level 4 warning are enabled if you pass /W4 to the compiler) for it

这篇博文:Visual C++ 是如此自由,其中涵盖了这个扩展注释:

This blog post: Visual C++ is so Liberal which covers this extension notes that:

使用禁用语言扩展 (/Za) 会导致错误:

Using Disable Language Extensions (/Za) makes it an error:

这篇关于绑定到临时的 Visual Studio 错误的非常量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)