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

标签 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;
}

此代码无法编译。谁能帮我弄清楚为什么? 不仅是这段代码,还有 this 中的代码也未能通过引用发送 std::unique_ptrstd::thread 有什么问题?

最佳答案

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

喜欢

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

关于c++ - 为什么我不能使用 std::thread 通过引用发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895127/

相关文章:

c++ - 未定义对 CreateCompatibleDC、BitBlt 等的引用?

c# - 如何在 C# 中的指定时间后取消后台工作程序

c# - 奇怪的引用行为(与 int 相同的内存地址)

c++ - friend 功能上的模板链接器错误

python - 将 MKL 优化的 numpy.dot() 与 3d 数组结合使用

c++ - pthread_cond_wait 和 pthread_mutex_unlock 是否冲突?

reference - 为什么在Rust中需要显式的生存期?

c++ - 使用 C++ 和标准 C 库以异步方式实现套接字连接读取超时处理的最佳方法

c++ - TLS 变量访问的结果未缓存