Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with r-values and l-values

I read recently on a whitepaper on C++11, that if I write,

void foo(X&)

This will be called for l-values but not for r-values

and if I write,

void foo(const X&)

This will be called for both r-value and l-value.

Could someone give me an example what this means here ?

like image 751
cpp11dev Avatar asked Jan 18 '26 04:01

cpp11dev


1 Answers

This function accepts a lvalue reference

void foo(X&)

and trying to call it with an rvalue would yield an error.

This function expects a const lvalue reference

void foo(const X&)

but there's a catch:

An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.

from cppreference

So it is true that this last function accepts both lvalue and rvalue parameters

struct X {};

void foo(X&) {
}

void fooC(const X&) {
}

int main() { 
   X obj;
   // foo(std::move(obj)); // Error - non-const
   foo(obj); // Valid
   fooC(obj); // Valid
   fooC(std::move(obj)); // Valid
}

For more information take a look at here: reference initialization or check [dcl.init.ref]/p5

like image 163
Marco A. Avatar answered Jan 20 '26 21:01

Marco A.