Home > Backend Development > C++ > Why Does Visual Studio Allow Non-Const Reference Binding to Temporaries?

Why Does Visual Studio Allow Non-Const Reference Binding to Temporaries?

Mary-Kate Olsen
Release: 2024-12-24 09:55:25
Original
900 people have browsed it

Why Does Visual Studio Allow Non-Const Reference Binding to Temporaries?

Visual Studio's Curious Case of Non-Const Reference Binding to Temporaries

Visual Studio's behavior towards binding non-const references to temporary objects has raised eyebrows among some programmers due to its seemingly contradictory nature. To understand the context, consider the following snippet of code:

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

Surprisingly, Visual Studio allows this code to compile while gcc identifies it as an error. This phenomenon has left many wondering about the rationale behind Visual Studio's approach.

Upon closer examination, it turns out that Visual Studio employs an older language extension. A Microsoft bug report sheds light on this issue, highlighting that Visual Studio permits binding temporary objects to non-const references. This behavior, however, can be corrected by using the /Za compiler option, which disables language extensions.

To further illustrate this extension, consider the following code:

struct A {};

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

int main()
{
    f2(f1()); // This line triggers an error with `/Za` enabled
}
Copy after login

As a workaround, Visual Studio supports a level 4 warning for such cases, which can be activated by specifying /W4 during compilation. However, it's worth noting that this approach still allows the code to compile, highlighting the flexibility of Visual Studio's extension.

The above is the detailed content of Why Does Visual Studio Allow Non-Const Reference Binding to Temporaries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template