Home >Backend Development >C++ >Why Does Visual Studio 2010 Allow Non-Const Reference Binding to Rvalues?

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

DDD
DDDOriginal
2024-11-01 20:57:02604browse

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:

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

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn