"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Visual Studio 2010 Allow Non-Const Reference Binding to Rvalues?

Why Does Visual Studio 2010 Allow Non-Const Reference Binding to Rvalues?

Published on 2024-11-04
Browse:843

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:

string foo() { return "hello"; }
int main() {
    string& tem = foo(); // Non-const reference to rvalue
}

Compiler Behavior Discrepancies

Contrastingly, other compilers exhibit more stringent behavior:

  • GCC issues a compile error, correctly identifying the illegal binding of a non-const reference to an rvalue.
  • Visual Studio 2008 provides a compile warning, acknowledging the potential issue but allowing compilation to proceed.

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3