Home >Backend Development >C++ >Why Does Visual Studio 2010 Allow Non-Const Reference Binding to Rvalues?
Allowing Non-Const Reference Binding to Rvalue: A VS2010 Anomaly
The C standard strictly forbids binding non-const references to rvalues. However, in a peculiar anomaly, Visual Studio 2010 (SP1) compiles the following code without any errors or warnings:
<code class="cpp">string foo() { return "hello"; } int main() { string& tem = foo(); // Non-const reference to rvalue }</code>
Compiler Behavior Discrepancies
Contrastingly, other compilers exhibit more stringent behavior:
VS2010 Anomaly Explanation
This unusual behavior in VS2010 stems from a known compiler extension. Unlike GCC and Visual Studio 2008, VS2010 allows non-const references to be bound to rvalues in certain cases, such as when the rvalue is generated by a function returning a temporary object.
While this extension defies the standard, it was likely implemented for convenience. However, it can lead to undefined behavior if the rvalue is modified after the reference is bound.
Consequences and Recommendations
This extension can introduce subtle bugs into code that relies on proper adherence to the C standard. Therefore, it is strongly recommended to avoid binding non-const references to rvalues, even in VS2010. Instead, always use const references when binding to rvalues, as intended by the standard.
The above is the detailed content of Why Does Visual Studio 2010 Allow Non-Const Reference Binding to Rvalues?. For more information, please follow other related articles on the PHP Chinese website!