当我看到这个网页时,我正在学习移动语义和右值引用https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n2027.html.有一段代码让我很困惑。
无移动语义
template <class T> swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a
a = b; // now we have two copies of b
b = tmp; // now we have two copies of tmp (aka a)
}
带有移动语义
template <class T> swap(T& a, T& b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
我们如何执行a
、b
和tmp
的两个副本。特别是a
和b
,因为它们是通过引用传递的。
设a'和b'为函数之前a
和b
中的值。
template <class T> swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a' (in a and tmp) and one of b' (in b)
a = b; // now we have two copies of b' (in a and b) and one of a' (in tmp)
b = tmp; // now we have two copies of a' (in b and tmp) and one of b' (in a)
}
这可能会有所帮助。
然后我们做移动版本:
template <class T> swap(T& a, T& b)
{
T tmp(std::move(a)); // a' is in tmp; b' is in b; a is moved-from
a = std::move(b); // a' is in tmp, b' is in a; b is moved-from
b = std::move(tmp); // a' is in b; b' is in a; tmp is moved-from
}
诀窍是区分变量CCD_ 8和存储在CCD_。