Error: Non-const Reference Bound to Temporary in Visual Studio
GCC raises an error when assigning a temporary object to a non-const reference. Surprisingly, Visual Studio allows this. Why the discrepancy?
The explanation lies in an old extension in Visual Studio. As noted in a bug report: "Temporary Objects Can be Bound to Non-Const References," Visual Studio allows temporary objects to be bound to non-const references, even though it can result in undefined behavior.
This behavior has been controversial. One response to the bug report notes that there is a level 4 warning for this error, which can be enabled with the "/W4" compiler flag.
However, there is a way to make this an error in Visual Studio: disable language extensions with the "/Za" flag. This is a useful workaround if you want to adhere to strict C standards and avoid potentially problematic code behavior.
To illustrate, consider the following example:
class Zebra { int x; }; Zebra goo() { Zebra z; return z; } void foo(Zebra &x) { Zebra y; x = y; foo(goo()); // Error in GCC, allowed in Visual Studio }
In Visual Studio, this code will compile without errors. However, in GCC, it will generate a compile error due to the temporary object being assigned to a non-const reference.
The above is the detailed content of Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects While GCC Doesn't?. For more information, please follow other related articles on the PHP Chinese website!