[英]why std::move uses std::remove_reference?
According to http://en.cppreference.com/w/cpp/utility/move 根据http://en.cppreference.com/w/cpp/utility/move
std::move
is declared as follows: std::move
声明如下:
template <typename T>
std::remove_reference<T>::type&& move(T&& t);
As far as my understanding goes, when code is templated, the deduction of T
in typename T
looses information about reference, so following: 至于我的理解去,当代码为模板,在扣除T
的typename T
失去有关参考信息,因此以下内容:
template <typename T>
void someFunction(T&& value);
when used like: 当像这样使用时:
int five=5;
someFunction(five);
then 然后
value
is of type int&
value
的类型为int&
T
is int
T
是int
or 要么
const float value = 5.25;
someFunction(value);
then 然后
value
is of type const float&
value
类型为const float&
T
is const float
. T
是const float
。 If this is so, then there is no point in move declaration to declare returned type as: std::remove_reference<T>::type&&
, because T is already not a reference. 如果是这样,那么在move声明中就没有必要将返回的类型声明为: std::remove_reference<T>::type&&
,因为T已经不是引用。
Moreover, if std::move
takes as argument a reference (l-value reference in practice), then returning static_cast<T&&>(t)
in std::move
in fact due to reference collapsing will return l-value reference or r-value reference, so it will behave more like std::forward
not move. 此外,如果std::move
将引用作为参数(实际上是l值引用),则实际上由于引用折叠而在std::move
中返回static_cast<T&&>(t)
会返回l值引用或r-值引用,因此其行为将更像std::forward
不动。 So what is a trick, that makes it work properly, that I do not understand? 那么,什么使我无法理解的窍门能够正常工作呢?
Your examples are incorrect: 您的示例不正确:
int five=5;
someFunction(five);
In this case, T
is deduced as int&
, not int
. 在这种情况下, T
推导为int&
,而不是int
。 The same goes for the second example; 第二个例子也是如此。 T
is deduced as const int&
. T
推导为const int&
。
As such, returning just T&&
would mean T&& &
, which is T&
due to reference collapsing rules. 因此,仅返回T&&
就意味着T&& &
,由于引用折叠规则,因此T&& &
就是T&
。
This is why the std::remove_reference
is required, to ensure that there are no references on the type to prevent reference collapsing from taking place. 这就是为什么需要std::remove_reference
原因,以确保类型上没有引用以防止引用崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.