为什么我不能使用std :: thread通过引用发送对象

Ank*_*rya 1 c++ multithreading reference

我的代码是这样的: -

#include <iostream>
#include <thread>
using namespace std;
void swapno (int &a, int &b)
{
    int temp=a;
    a=b;
    b=temp;
}
int main()
{
    int x=5, y=7;
    cout << "x = " << x << "\ty = " << y << "\n";
    thread t (swapno, x, y);
    t.join();
    cout << "x = " << x << "\ty = " << y << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码无法编译.任何人都可以帮我解释原因吗?不仅如此代码,但是代码也无法发送std::unique_ptr的参考.怎么了std::thread

Som*_*ude 8

问题是std::thread 复制其参数并在内部存储它们.如果要通过引用传递参数,则需要使用std::refstd::cref函数来创建引用包装器.

喜欢

thread t (swapno, std::ref(x), std::ref(y));
Run Code Online (Sandbox Code Playgroud)