C++11 – Use of Rvalue Reference Members

c++c++11rvalue-reference

I was wondering what use an rvalue reference member has

class A {
  // ...
  // Is this one useful?
  Foo &&f;
};

Does it have any benefits or drawbacks compared to an lvalue reference member? What is a prime usecase of it?

Best Answer

I've seen one very motivating use case for rvalue reference data members, and it is in the C++0x draft:

template<class... Types>
tuple<Types&&...>
forward_as_tuple(Types&&... t) noexcept;

Effects: Constructs a tuple of references to the arguments in t suitable for forwarding as arguments to a function. Because the result may contain references to temporary variables, a program shall ensure that the return value of this function does not outlive any of its arguments. (e.g., the program should typically not store the result in a named variable).

Returns: tuple<Types&&...>(std::forward<Types>(t)...)

The tuple has rvalue reference data members when rvalues are used as arguments to forward_as_tuple, and otherwise has lvalue reference data members.

I've found forward_as_tuple subsequently helpful when needing to catch variadic arguments, perfectly forward them packed as a tuple, and re-expand them later at the point of forwarding to a functor. I used forward_as_tuple in this style when implementing an enhanced version of tuple_cat proposed in LWG 1385:

http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1385