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:
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.
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