使用右值引用成员?
我想知道右值引用成员有什么用处
class A {
// ...
// Is this one useful?
Foo &&f;
};
与左值引用成员相比它有什么优点或缺点?它的主要用途是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我看到了右值引用数据成员的一个非常令人兴奋的用例,它位于 C++0x 草案中:
当右值用作forward_as_tuple 的参数时,元组具有右值引用数据成员,否则具有左值引用数据成员。
我发现,当需要捕获可变参数时,forward_as_tuple 随后很有帮助,将它们完美地转发为元组,并在转发到函子时重新扩展它们。在实现 LWG 1385 中提出的 tuple_cat 的增强版本时,我以这种风格使用了forward_as_tuple:
I've seen one very motivating use case for rvalue reference data members, and it is in the C++0x draft:
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
根据 Stephan T. Lavavej,右值引用数据成员没有用。
According to Stephan T. Lavavej, rvalue reference data members have no use.
只是在这里大声思考,但它在函子中没有用处吗?构造函数通常用于“柯里化”,在实际函数调用之前提前绑定一些参数。
因此,在这种情况下,类成员只是即将到来的函数调用的临时场所(或手动实现的闭包),并且我认为右值引用没有任何意义。
但在“常规”非函子类中,我看不出有什么意义。
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.
在这种特定情况下,没有理由使用右值引用。它不会给你带来任何你以前做不到的事情。
但您可能想用参数化类型定义数据成员。例如,std::tuple 将支持左值和右值引用数据成员。这样,您就可以对表达式的值类别进行编码,这对于“延迟完美转发”可能会派上用场。标准草案甚至包括形式的函数模板
但老实说我不确定它的用处。
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
But I'm honestly not sure about its usefulness.