我发现自己并没有完全理解它的逻辑std::move().
起初,我用谷歌搜索它,但似乎只有关于如何使用的文件std::move(),而不是它的结构如何工作.
我的意思是,我知道模板成员函数是什么,但是当我std::move()在VS2010中查看定义时,它仍然令人困惑.
std :: move()的定义如下.
template<class _Ty> inline
typename tr1::_Remove_reference<_Ty>::_Type&&
move(_Ty&& _Arg)
{ // forward _Arg as movable
return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg);
}
Run Code Online (Sandbox Code Playgroud)
首先对我来说奇怪的是参数,(_Ty && _Arg),因为当我调用函数时,如下所示,
// main()
Object obj1;
Object obj2 = std::move(obj1);
Run Code Online (Sandbox Code Playgroud)
它基本上等于
// std::move()
_Ty&& _Arg = Obj1;
Run Code Online (Sandbox Code Playgroud)
但正如您已经知道的那样,您不能直接将LValue链接到RValue引用,这让我觉得它应该是这样的.
_Ty&& _Arg = (Object&&)obj1;
Run Code Online (Sandbox Code Playgroud)
但是,这是荒谬的,因为std :: move()必须适用于所有值.
所以我想要完全理解它是如何工作的,我也应该看看这些结构.
template<class _Ty>
struct _Remove_reference
{ // remove reference
typedef _Ty _Type;
};
template<class _Ty>
struct _Remove_reference<_Ty&>
{ // remove reference
typedef _Ty _Type;
}; …Run Code Online (Sandbox Code Playgroud) I tried implementing std::move, which uses std::remove_reference, however it seems to work without it. Please, give me an example in which my implementation will fails whithout std::remove_reference.
template <class type> type && move(type & source) { return (type &&) source; }
template <class type> type && move(type && source) { return (type &&) source; }
Run Code Online (Sandbox Code Playgroud)
Is std::remove_reference used only to avoid overloading std::move?
Here is a test class to help you:
class test {
public : …Run Code Online (Sandbox Code Playgroud) #include <type_traits>
template<class T>
typename std::remove_reference<T>::type&& move(T&& v)
{
return v;
}
void main()
{
int a;
move(a);
}
Run Code Online (Sandbox Code Playgroud)
为什么这段代码不能编译?
错误C2440:'return':无法在'int &&'中转换'int'
根据http://en.cppreference.com/w/cpp/utility/move
std::move 声明如下:
template <typename T>
std::remove_reference<T>::type&& move(T&& t);
Run Code Online (Sandbox Code Playgroud)
至于我的理解去,当代码为模板,在扣除T中typename T失去约的参考信息,所以以下内容:
template <typename T>
void someFunction(T&& value);
Run Code Online (Sandbox Code Playgroud)
使用时如:
int five=5;
someFunction(five);
Run Code Online (Sandbox Code Playgroud)
然后
value 是类型的 int&T 是 int要么
const float value = 5.25;
someFunction(value);
Run Code Online (Sandbox Code Playgroud)
然后
value 是类型的 const float&T是const float.如果是这样,那么移动声明中没有必要将返回的类型声明为:
std::remove_reference<T>::type&&,因为T已经不是引用了.
此外,如果std::move采用作为参数的引用(实际上1-值参考),然后返回static_cast<T&&>(t)在std::move实际上由于参照塌缩将返回-1-参考值或R值的参考,所以它会表现得更像std::forward不移动.那么什么是诀窍,让它运作正常,我不明白?