這次我遇到std::thread
&的另一個問題,同時應用std::move
來交換2個值。我的代碼說: -在std :: thread中使用std :: move
#include <iostream>
#include <thread>
using namespace std;
void swapno (int &&a, int &&b)
{
int temp=move(a);
a=move(b);
b=move(temp);
}
int main()
{
int x=5, y=7;
cout << "x = " << x << "\ty = " << y << "\n";
// swapno (move(x), move(y)); // this works fine
thread t (swapno, move(x), move(y));
t.join();
cout << "x = " << x << "\ty = " << y << "\n";
return 0;
}
輸出: -
x = 5 y = 7
x = 5 y = 7
現在,什麼是錯的這個方法?爲什麼這樣的代碼顯示出這樣的行爲?我如何糾正它?
該線程使用'x'和'y'的副本不是它們的引用。您可以改爲將指針傳遞給'x'和'y'。 – Jerome
原因與您之前的問題相同。另外,使用'std :: swap'。 – juanchopanza
你是怎麼從「[你必須將它包裝在std :: ref(http://stackoverflow.com/a/33895159)」中去使用&&? – Default