Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are objects inside rvalue referenced object, also rvalue referenced?

Are objects inside rvalue referenced object, also rvalue referenced?

struct A{
};

struct B{
   A a2;
};

//template<class B>
void test(B &&b){

    // 1. Is this the correct way?
    auto &&in3 = std::forward<B>(b).a2;
    std::cout << std::is_rvalue_reference<decltype(in3)>::value;
    // return true

    // 2. or this?
    auto &&in4 = b.a2;
    std::cout << std::is_rvalue_reference<decltype(in4)>::value;    
    // return false        
}

test(B());

http://coliru.stacked-crooked.com/a/bcf0f7dc4cc0440e

like image 610
tower120 Avatar asked Jun 24 '14 07:06

tower120


People also ask

Is an rvalue reference an rvalue?

An rvalue reference is formed by placing an && after some type. An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.

Can you pass an lvalue to an rvalue reference?

Explanation: If you pass an lvalue T to enqueue , U will deduce to T& , and the forward will pass it along as an lvalue, and you'll get the copy behavior you want. If you pass an rvalue T to enqueue , U will deduce to T , and the forward will pass it along as an rvalue, and you'll get the move behavior you want.

Are references a lvalue?

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

Can you take the address of an rvalue?

2) non-modifiable lvalues, which are const. rvalue — The expression that refers to a disposable temporary object so they can't be manipulated at the place they are created and are soon to be destroyed. An address can not be taken of rvalues. An rvalue has no name as its a temporary value.


1 Answers

Yes, members of rvalues are themselves rvalues. This was clarified by DR 421

But that is irrelevant here:

auto &&in4 = b.a2;

b is not an rvalue, it's an lvalue (simple rule of thumb: it has a name).

To restore the value category it had when passed to the function you need to forward it

like image 139
Jonathan Wakely Avatar answered Sep 19 '22 15:09

Jonathan Wakely