前进或移动 [英] Forward or Move

查看:87
本文介绍了前进或移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些前进和后退的有效用法吗?
f3和f4相同吗?
这样做有危险吗?
谢谢!

#include <utility>
class A {};
A f1() {
  A a;
  return a;   // Move constructor is called
}
A f2(A&& a) {
  return a;   // Copy constructor is called, which is what I try to avoid.
}
A f3(A&& a) {
  return std::forward<A&&>(a); // Move constructor is called
}
A f4(A&& a) {
  return std::move(a); // Move constructor is called
}

解决方案

std::forward之所以存在,是因为&&如何在类型推导下起作用.

根据类型推导,T&&中的T将绑定到3种可能性之一.如果从左值int&推导,则T将绑定到int&.那么int& &&只是int&.如果从左值int const&推导,则T将绑定到int const&,并且int const& &&int const&.如果从某种右值int推导出来,则T将绑定到int,而int&&int&&.

std::forward是用于反转该映射的实用程序功能. std::forward<>的三个相关签名是:T& std::forward<T&>(T&)T const& std::forward<T const&>(T const&)T&& std::forward<T>(T&&)

当进行称为完美转发"的技术时,所有这些最终都非常有用,在这种情况下,您可以在类型推导上下文中使用T&&t,然后std::forward<T>(t)传递从中推导的相同类型"转到另一个电话.

请注意,上面有一些简化之处.例如,还有T const&&的可能性,它在类型上非常晦涩.我可能掩盖了类型推导的工作原理的一些细节,术语rvaluelvalue不能完全反映C ++ 11中不同类型变量值的完整5倍(或者是6?).

Are these valid usage of move and forward?
Are f3 and f4 the same?
Is it dangerous to do so?
Thank you!

#include <utility>
class A {};
A f1() {
  A a;
  return a;   // Move constructor is called
}
A f2(A&& a) {
  return a;   // Copy constructor is called, which is what I try to avoid.
}
A f3(A&& a) {
  return std::forward<A&&>(a); // Move constructor is called
}
A f4(A&& a) {
  return std::move(a); // Move constructor is called
}

解决方案

std::forward exists because of a quirk in how && works under type deduction.

Under type deduction, the T in T&& will bind to one of 3 possibilities. If being deduced from an lvalue int&, T will bind to int&. Then int& && is just a int&. If being deduced from an lvalue int const&, T will bind to int const&, and int const& && is int const&. If being deduced from an rvalue int of some kind, T will bind to int, and int&& is int&&.

std::forward is a utility function to reverse that map. The three pertinent signatures of std::forward<> are: T& std::forward<T&>(T&) or T const& std::forward<T const&>(T const&) or T&& std::forward<T>(T&&)

All of this ends up being exceedingly useful when doing the technique known as "perfect forwarding", where you use T&&t in a type deduction context, then std::forward<T>(t) to pass on the "same type" as was deduced from to another call.

Note that there are a few simplifying lies above. There are is also the possibility of T const&& which is pretty obscure type-wise, as an example. I probably glossed over some details of how the type deduction works, and the terms rvalue and lvalue don't fully reflect the full 5-fold (or is it 6?) different kinds of variable values in C++11.

这篇关于前进或移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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