I have the following code
string three()
{
return "three";
}
void mutate(string& ref)
{
}
int main()
{
mutate(three());
return 0;
}
You can see I am passing three() to mutate method. This code compiles well. My understanding is, temporaries can't be assigned to non-const references. If yes, how this program is compiling?
Any thoughts?
Edit:
Compilers tried : VS 2008 and VS2010 Beta
An lvalue reference can bind to an lvalue, but not to an rvalue.
“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variable.
Such a reference is called an lvalue reference to a const value (sometimes called a reference to const or a const reference). In the above program, we bind const reference ref to modifiable lvalue x . We can then use ref to access x , but because ref is const, we can not modify the value of x through ref .
An lvalue refers to an object that persists beyond a single expression. An rvalue is a temporary value that does not persist beyond the expression that uses it.
It used to compile in VC6 compiler, so I guess to maintain backward comptibility VS2008 is supporting this non-standard extension. Try with /Za (disable language extension) flag, you should get an error then.
It is VC++'s evil extension. If You oompile with /W4 then the compiler will warn you. I guess you are reading the Rvalue References: C++0x Features in VC10, Part 2. This article had also mentioned that issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With