使用右值引用成员? [英] Use of rvalue reference members?

查看:329
本文介绍了使用右值引用成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道右值引用成员使用了什么

  class A {
// ...
//这是有用的吗?
Foo&& f;
};

与左值引用成员相比,它有什么优点或缺点吗?什么是它的主要用例?

解决方案

我已经看到一个非常有用的用例的右值引用数据成员,在C ++ 0x草稿中:

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




效果:构造
的元组引用参数在t
中适合作为参数
转发给函数。因为结果可能
包含对临时
变量的引用,程序应确保
此函数的返回值
不超过其任何参数。
(例如,程序应该通常
不将结果存储在命名的
变量中)。



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


当rvalue用作forward_as_tuple的参数时,元组具有右值引用数据成员,否则有左值引用数据成员。



发现forward_as_tuple后来有帮助,当需要捕获可变参数,完美地转发它们打包为一个元组,并重新扩展他们在转发到函子的时间点。我在这种风格中使用forward_as_tuple在实现LWG 1385中提出的tuple_cat的增强版本时:



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

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?

解决方案

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

这篇关于使用右值引用成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆