【C++多線程系列】【二】線程啓動函數的參數傳遞需類型匹配

給線程的執行函數傳遞參數時,必定要參數匹配,不然會有編譯問題。不一樣的編譯器處理可能不同。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

相關文章
相關標籤/搜索