Non-Constant Reference Bound to Temporary: Visual Studio Anomaly
This issue arises when compiling code that attempts to bind a non-constant reference to a temporary object. While Visual Studio allows such code to compile, other compilers, like gcc, identify it as a compilation error.
Explanation
In the example provided:
class Zebra {int x;}; Zebra goo() {Zebra z; return z;} void foo(Zebra &x) { Zebra y; x = y; foo(goo()); }
The code attempts to bind a non-constant reference (Zebra &x) to a temporary object returned by the function goo(). According to the C standard, this should result in a compile error.
Visual Studio Extension
However, Visual Studio has an old extension that allows for this behavior. This extension essentially treats references to temporary objects as if they were references to non-temporary objects.
This extension was introduced to support legacy code bases. However, it can lead to unexpected behavior and is generally not recommended.
Recommended Approach
To avoid these anomalies, it is best to disable the extension using the /Za compiler flag. This will ensure that the code adheres to the C standard and will be consistently treated by different compilers.
The above is the detailed content of Why Does Visual Studio Compile Non-Constant References to Temporaries While Other Compilers Don't?. For more information, please follow other related articles on the PHP Chinese website!