为什么我不能使用 std::thread 通过引用发送对象
why can't I send object by reference using std::thread
我的代码如下:-
#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_ptr
。std::thread
出了什么问题?
问题是std::thread
复制其参数并将其存储在内部。如果要通过引用传递参数,则需要使用std::ref
或std::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;
}
你应该得到同样的结果;)
相关文章:
- 引用对象成员函数的成员函数
- 从 Base 引用对象调用派生类的成员
- 转换引用对象的边界框?
- 现代编译器会优化只引用对象子集的局部变量吗
- l值引用对象上的Constexpr成员函数:Clang和gcc不同意
- 将 const 类型引用对象注册为类成员对象C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 无法用2D矢量成员引用对象
- 在由引用对象传递中访问由引用对象传递的变量
- 如何使用QString引用对象名称
- 使用自动迭代器引用对象
- C++ 在另一个对象中引用对象的当前状态
- 使用共享对象和引用对象进行引用计数
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 引用对象的动态类型何时可以更改
- 引用对象内部的指针
- C++从全局静态函数中引用对象
- C++如何仅在没有其他人直接或间接引用对象指针时删除该指针
- 如何使用C++引用对象
- 为什么引用对象仅保存特定类型的引用