【发布时间】:2011-07-28 14:44:16
【问题描述】:
std::move这个函数我不是很懂
template <class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
为什么是remove_reference?
谁能给我一个简单的解释?
【问题讨论】:
标签: c++ c++11 move-semantics
std::move这个函数我不是很懂
template <class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
为什么是remove_reference?
谁能给我一个简单的解释?
【问题讨论】:
标签: c++ c++11 move-semantics
想想如果T 是一个左值引用会发生什么,例如MyClass &。在这种情况下,T && 将变为MyClass & &&,并且由于引用折叠规则,这将再次转换为MyClass &。为了获得正确的结果,typename remove_reference<MyClass&>::type&& 首先从类型中删除任何引用修饰,因此MyClass & 映射到MyClass,然后将右值引用应用于它,产生MyClass &&。
【讨论】:
因为对左值引用的右值引用会衰减为左值引用,并且返回左值引用的语义与您对move 所期望的语义不同。
编辑: 呵呵,为什么要投反对票?看看这段代码:
template < typename T > T&& func(T&& x) { return x; }
int main()
{
int x;
int &y = func(x);
}
延伸阅读:http://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html
【讨论】: