【问题标题】:why can't I send object by reference using std::thread [duplicate]为什么我不能使用 std::thread 通过引用发送对象 [重复]
【发布时间】:2015-11-24 13:35:31
【问题描述】:

我的代码是这样的:-

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

此代码无法编译。谁能帮我解决为什么? 不仅此代码,而且this 中的代码也未能通过引用发送std::unique_ptrstd::thread 有什么问题?

【问题讨论】:

  • 您可以通过使用std::ref(即thread t (swapno, std::ref(x), std::ref(y));)来明确引用。

标签: c++ multithreading reference


【解决方案1】:

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

喜欢

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

【讨论】:

    【解决方案2】:

    您可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2015-08-22
      • 1970-01-01
      相关资源
      最近更新 更多