我想知道右值引用成员有什么用处
class A {
// ...
// Is this one useful?
Foo &&f;
};
与左值引用成员相比,它有什么优点或缺点吗?它的主要用例是什么?
最佳答案
我看到了一个非常鼓舞人心的右值引用数据成员用例,它在 C++0x 草案中:
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)...)
当右值用作 forward_as_tuple 的参数时,元组具有右值引用数据成员,否则具有左值引用数据成员。
我发现 forward_as_tuple 随后在需要捕获可变参数时很有帮助,将它们完美地打包为一个元组,然后在转发到仿函数时重新展开它们。在实现 LWG 1385 中提出的 tuple_cat 的增强版本时,我使用了这种风格的 forward_as_tuple:
http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1385
关于c++ - 使用右值引用成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774420/