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()); }
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 }
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!