Home  >  Article  >  Backend Development  >  Why Does VS2010 Allow Non-Const References to be Bound to Rvalues?

Why Does VS2010 Allow Non-Const References to be Bound to Rvalues?

DDD
DDDOriginal
2024-10-28 03:22:31632browse

Why Does VS2010 Allow Non-Const References to be Bound to Rvalues?

Non-const Reference Binding to Rvalue: A VS2010 Anomaly

In C , binding a non-const reference to an rvalue is generally considered an error. However, in Visual Studio 2010, the following code compiles without any errors or warnings:

<code class="cpp">string foo() { return "hello"; }
int main() 
{
    //below should be illegal for binding a non-const (lvalue) reference to a rvalue
    string& tem  = foo();   

    //below should be the correct one as only const reference can be bind to rvalue(most important const)
    const string& constTem = foo();   
}</code>

This behavior is inconsistent with other compilers like GCC and VS2008, which raise compile errors or warnings for such code. This discrepancy has raised questions about whether it is a bug in VS2010.

Explanation

The behavior of VS2010 in this case is attributed to a known extension in the VS compilers. Historically, these compilers have allowed non-const references to be bound to rvalues without explicit const qualification. This behavior was introduced as a convenience for programmers and is not considered a standard C feature.

In the example code, the lack of any errors or warnings in VS2010 can be explained as follows:

  • The compiler recognizes the return value of foo() as an rvalue.
  • It interprets the string& tem declaration as a non-const reference to a string.
  • However, due to the extension in the VS compilers, it allows the reference to be bound to the rvalue returned by foo().

Conclusion

The behavior of VS2010 in allowing non-const references to be bound to rvalues without errors or warnings is not standard C and is considered an extension. While it may be useful in some cases, it can also lead to unexpected behavior and is generally discouraged in favor of using const references for binding to rvalues.

The above is the detailed content of Why Does VS2010 Allow Non-Const References to be Bound 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