c++多线程传递参数三种形式(值传递,引用,指针)

#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
	MyClass() { cout << "构造函数" << endl; };
	MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
	~MyClass() { cout << "析构函数" << endl; };

private:

};

//值拷贝
void func_value(int a, MyClass mm) {
	cout << "值拷贝" << endl;
	return;
}

int main() {
	int aa = 10;
	MyClass my;
	thread task1(func_value, aa, my);
	task1.join();
	
	return 0;
}

 值传递)aa,my对象以值传递形式传递给task1指针。my对象创建调用构造函数,my对象传递给子线程调用拷贝构造,my对象传递给mm又调用一次拷贝构造,所以:

构造函数
拷贝构造函数
拷贝构造函数
值传递
析构函数
析构函数
析构函数

 

#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
	MyClass() { cout << "构造函数" << endl; };
	MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
	~MyClass() { cout << "析构函数" << endl; };

private:

};

值拷贝
//void func_value(int a, MyClass mm) {
//	cout << "值传递" << endl;
//	return;
//}
//指针传递
void func_p(int* a, MyClass* mm) {
	cout << "指针传递" << endl;
	return;
}

int main() {
	int aa = 10;
	MyClass my;
	/*thread task1(func_value, aa, my);
	task1.join();*/
	thread task2(func_p, &aa, &my);
	//task2.join();
	task2.detach();
	
	return 0;
}

 output:

构造函数
指针传递
析构函数

指针传递)aa,my以指针的方式传递给函数指针,不会进行内存的复制,但主线程与子线程分离,主线程先执行结束释放了资源,子线程拿到的是垃圾值,该例不会,因为子线程够快,并且子线程也没访问a,mm内容。

#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
	MyClass() { cout << "构造函数" << endl; };
	MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
	~MyClass() { cout << "析构函数" << endl; };

private:

};

值拷贝
//void func_value(int a, MyClass mm) {
//	cout << "值传递" << endl;
//	return;
//}
指针传递
//void func_p(int* a, MyClass* mm) {
//	cout << "指针传递" << endl;
//	return;
//}
//引用传递
void func_ref(int& a, MyClass& mm) {
	cout << "引用传递" << endl;
	return;
}
int main() {
	int aa = 10;
	MyClass my;
	/*thread task1(func_value, aa, my);
	task1.join();*/
	//thread task2(func_p, &aa, &my);
	task2.join();
	//task2.detach();
	thread task3(func_ref, ref(aa), ref(my));
	task3.detach();
	return 0;
}

引用传递)引用与指针的形式差不多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CV_er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值