Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One VS2010 bug ? Allowing binding non-const reference to rvalue WITHOUT EVEN a warning?

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();   
}
  1. GCC is the good one to give a compile error: invalid initialization of non-const reference of type std::string& from a temporary of type std::string
  2. VS2008 is not too bad as at least it gives a compile warning: warning C4239: nonstandard extension used : 'initializing' : conversion from std::string to std::string & A non-const reference may only be bound to an lvalue
  3. Here comes the problematic one - VS2010(SP1) comples fine WITHOUT any error or warning, WHY ??!! I know rvalue reference in VS2010 can be used to bind with rvalue but I am NOT using &&, instead in the demo code, I was just using non-const lvalue reference !

Can somone help me explain the behavior of VS2010 here? Is it a bug !? Thanks

like image 704
RoundPi Avatar asked Aug 25 '11 11:08

RoundPi


2 Answers

That is a known issue/feature of the VS compilers. They have always allowed that and there does not seem to be any push into removing that extension.

like image 97
David Rodríguez - dribeas Avatar answered Nov 15 '22 17:11

David Rodríguez - dribeas


The compiler will issue an error with Disable Language Extensions turned on, and a warning at /W4. However, removing this code will break previously compiling code, and Microsoft is very reluctant to do that. This is also why they won't fix their SFINAE support.

like image 31
Puppy Avatar answered Nov 15 '22 19:11

Puppy