Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding temporary to a lvalue reference

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

like image 789
Navaneeth K N Avatar asked Aug 28 '09 06:08

Navaneeth K N


People also ask

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.

What is an lvalue reference?

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

Is const reference an lvalue?

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 .

What are Lvalues and Rvalues?

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.


2 Answers

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.

like image 74
Naveen Avatar answered Oct 02 '22 16:10

Naveen


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.

like image 24
yoco Avatar answered Oct 02 '22 17:10

yoco