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

why can't I send object by reference using std::thread

本文关键字:引用 对象 thread 不能 std 为什么      更新时间:2023-10-16

我的代码如下:-

#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;
}

此代码无法编译。有人能帮我解释一下为什么吗?不仅此代码,而且此代码中的代码也未能通过引用发送std::unique_ptrstd::thread出了什么问题?

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

thread t (swapno, std::ref(x), std::ref(y));

您可以这样做,而不是:

    #include <iostream>
    #include <thread>
    void swapno (int *a, int *b)
    {
        int temp=*a;
        *a=*b;
        *b=temp;
    }
    int main()
    {
        int x = 5, y = 7;
        std::cout << "x = " << x << "ty = " << y << "n";
        std::thread t (swapno, &x, &y);
        t.join();
        std::cout << "x = " << x << "ty = " << y << "n";
        return 0;
    }

你应该得到同样的结果;)