c++ - 使用右值引用成员?

标签 c++ c++11 rvalue-reference

我想知道右值引用成员有什么用处

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/

相关文章:

c++ - 在 C++ 中使用 sprintf() 和 sscanf() 时出现意外行为?

c++ - 为什么成员函数不能用作模板参数?

c++ - 带有浮点/ double 值的 std::numeric_limits<T>::min() 问题

c++ - 为什么 const 限定符允许临时对象或右值?

c++ - Boost.Move 与其他 Boost 库的集成

具有两个运算符的 C++11 歧义错误(一个左值第二个右值)

c++ - 在关卡/房间之间移动角色

c++ - 当我添加一个新元素时,Unordered_map 表现得很奇怪

c++ - 如何使用智能指针跟踪类的对象?

c++ - 从 vector 中写入/读取的奇怪行为