给线程的执行函数传递参数时,必定要参数匹配,不然会有编译问题。不一样的编译器处理可能不同。ios
1.vs2013编译经过。函数
#include<iostream> #include<thread> using namespace std; typedef struct _A { int a; }A; void f(A &a) { cout << a.a << endl; a.a++; cout << a.a << endl; } int main(int argc, int * argv[]) { A a = { 1 }; cout << a.a << endl; // 这里vs2013编译经过,vs2017编译失败 thread t(f,a); t.join(); cout << a.a << endl; system("pause"); }
2.vs2017编译失败spa
#include<iostream> #include<thread> using namespace std; typedef struct _A { int a; }A; void f(A &a) { cout << a.a << endl; a.a++; cout << a.a << endl; } int main(int argc, int * argv[]) { A a = { 1 }; cout << a.a << endl; // 这里vs2013编译经过,vs2017编译失败 thread t(f,a); t.join(); cout << a.a << endl; system("pause"); }
提示参数类型不匹配,即函数f参数所需的类型与传入的参数类型不匹配。线程
修改以下,编译经过。code
#include<iostream> #include<thread> using namespace std; typedef struct _A { int a; }A; void f(A &a) { cout << a.a << endl; a.a++; cout << a.a << endl; } int main(int argc, int * argv[]) { A a = { 1 }; cout << a.a << endl; thread t(f,std::ref(a)); t.join(); cout << a.a << endl; system("pause"); }
结果以下:编译器
总结:给线程启动函数传递参数时,类型必定要匹配。不然不是编译问题,就是运行结果与预期不符。io