无法理解 std::move 的实现
Can't understand the implementation of std::move
这是 std::move()
的一个可能实现。它不完全符合标准的细节,但非常接近:
template<class T>
typename std::remove_reference<T>::type&&
myMove( T&& Arg )
{
return ( ( typename std::remove_reference<T>::type&& )Arg );
}
我不明白为什么如果我们用 T&&
替换 typename std::remove_reference<T>::type&&
就不起作用,即
template<class T>
typename std::remove_reference<T>::type&&
myMove( T&& Arg )
{
return ( (T&&) Arg );
}
问题不在于移动,而在于 T&&
发生的引用崩溃。
关于这个的评论很好 here and these Q&A here, and here。
我将专注于演员表 (T&&)
以及为什么它不起作用。
鉴于上面列出的参考折叠规则;
T& &
变为 T&
T& &&
变为 T&
T&& &
变为 T&
T&& &&
变为 T&&
当 T
被推断为左值引用时出现问题,然后 T&&
变为 T& &&
并折叠为 T&
,给定转换,您只需转换它返回到左值引用,而您还没有获得使移动发生的右值引用。
std::remove_reference<T>::type
用于删除所有引用,然后 &&
添加回右值引用,从而确保进行正确的转换。
typename
用于消除成员变量的成员类型歧义。
这是 std::move()
的一个可能实现。它不完全符合标准的细节,但非常接近:
template<class T>
typename std::remove_reference<T>::type&&
myMove( T&& Arg )
{
return ( ( typename std::remove_reference<T>::type&& )Arg );
}
我不明白为什么如果我们用 T&&
替换 typename std::remove_reference<T>::type&&
就不起作用,即
template<class T>
typename std::remove_reference<T>::type&&
myMove( T&& Arg )
{
return ( (T&&) Arg );
}
问题不在于移动,而在于 T&&
发生的引用崩溃。
关于这个的评论很好 here and these Q&A here, and here。
我将专注于演员表 (T&&)
以及为什么它不起作用。
鉴于上面列出的参考折叠规则;
T& &
变为T&
T& &&
变为T&
T&& &
变为T&
T&& &&
变为T&&
当 T
被推断为左值引用时出现问题,然后 T&&
变为 T& &&
并折叠为 T&
,给定转换,您只需转换它返回到左值引用,而您还没有获得使移动发生的右值引用。
std::remove_reference<T>::type
用于删除所有引用,然后 &&
添加回右值引用,从而确保进行正确的转换。
typename
用于消除成员变量的成员类型歧义。