在学习c++ thread时候遇到一个小小的疑惑。功能都可以实现,但是区别是一个直接引用对象,另一个是获取对象的地址,
向大家请教一下这2者有什么区别?
源码:
#include<iostream>
#include<thread>
using namespace std;
class mm
{
public:
void printf()
{
cout << "nihao" << endl;
}
};
int main()
{
mm a;
thread thread1(&mm::printf,&a);
//thread thread1(&mm::printf,a);//这一行没有添加取地址符号
thread1.join();
}
给你加点东西就清楚了
#include<iostream>
#include<thread>
using namespace std;
class mm
{
int n;
public:
mm(int _n):n(_n){}
void printf()
{
this->n=100;
cout << "nihao" << endl;
}
void show() {
cout<<n<<endl;
}
};
int main()
{
mm a(10);
mm b(10);
thread thread1(&mm::printf,a);
thread thread2(&mm::printf,&b);//这一行没有添加取地址符号
thread1.join();
thread2.join();
a.show();
b.show();
}
a 是复制过去,所以它的n值没有改变
b是传地址,所以线程结束后n值发生变化