當我看到這個網頁 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
uj5u.com熱心網友回復:
設 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
}
訣竅是區分變數 a和存盤在a.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516300.html
上一篇:顯示來自std::condition_variable::wait的解鎖
下一篇:在Windows桌面應用程式(VS2022/C 14)中使用FirebaseSDK(VS2019/C 11)構建錯誤
