Temporary Objects Bound to Non-Const References in Visual Studio
The issue of whether temporary objects can be bound to non-const references has been a subject of debate among programmers, particularly in the context of Visual Studio. The question arises when code compiles in Visual Studio but generates errors in other compilers, such as gcc.
To understand the problem, consider the following 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 without errors. However, gcc treats it as a compile-time error. This discrepancy raises the question of the validity of binding temporary objects to non-const references.
To address this, it's important to note that Microsoft introduced an extension to their compiler, which allows for the binding of temporary objects to non-const references. This behavior is contrary to the C standard, which prohibits such bindings.
The Microsoft bug report "Temporary Objects Can be Bound to Non-Const References" provides further insight into this behavior. It states that this extension is an exception to the standard, enabled by default in Visual Studio.
However, the bug report also suggests that using the "/Za" compiler option, which disables language extensions, can cause the code to fail compilation, following the C standard. This indicates that Visual Studio's behavior in this case is a deliberate departure from the standard.
So, while Visual Studio allows the binding of temporary objects to non-const references, it is an extension that deviates from the C standard. Compilers that adhere strictly to the standard will generate errors when encountering such code. It is recommended to exercise caution when using this extension, as it may lead to unexpected behavior or portability issues.
The above is the detailed content of Can Temporary Objects Be Bound to Non-Const References in Visual Studio?. For more information, please follow other related articles on the PHP Chinese website!