I was wondering what use an rvalue reference member has
class A {
// ...
// Is this one useful?
Foo &&f;
};
Does it have any bene
According to Stephan T. Lavavej, rvalue reference data members have no use.
[at 31:00] The thing I've seen programmers do when they get hold of rvalue references is that, they start to go a little crazy, because they're so powerful. They start saying "Oh, I'm gonna have rvalue reference data members, I'm gonna have rvalue reference local variables, I'm gonna have rvalue reference return values!" And then they write code like this: [...]
class A {
// ...
// Is this one useful?
Foo &&f;
};
In this specific case, there is no reason to use an rvalue reference. It doesn't buy you anything you couldn't have done before.
But you may want to define data members with parameterized types. std::tuple is going to support lvalue and rvalue reference data members, for example. This way it allows you to codify an expression's value category which might come in handy for "delayed perfect forwarding". The standard draft even includes a function template of the form
template<class Args...>
tuple<Args&&...> pack_arguments(Args&&...args);
But I'm honestly not sure about its usefulness.
Just thinking out loud here, but wouldn't it have a use in functors? The constructor is often used for "currying", binding some parameters in advance, before the actual function call.
So in this context, the class member is just a staging ground (or a manually implemented closure) for the upcoming function call, and I see no reason why a rvalue reference wouldn't be meaningful there.
But in "regular" non-functor classes, I don't see much point.
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