C++多线程临时对象创建

#include<iostream>
#include<thread>

using namespace std;


//void myPrint(const int &i, char *buf)
//void myPrint(const int i, const string &buf)
//{
//	cout << i << endl;
//
//	//分析认为,i并不是marv的引用,实际是值传递。可以认为,即使主线程detach了子线程,
//	//子线程用了i值,仍然是安全的
//	//指针是有问题的,不推荐引用和指针
//	cout << buf.c_str() << endl;
//
//	return;
//}



//主线程使用类建立对象,执行顺序测试
class A {
public:
	int m_i;
	//类型转换构造函数,可以把int整型转换成类A对象
	A(int a) :m_i(a) { cout << "A::A(int a)构造函数执行!, 地址是:" << this << endl; }
	A(const A &a) :m_i(a.m_i) { cout << "A::A(const A)拷贝构造函数执行!地址是:" <<this << endl; }
	~A(){ cout << "A::~A()析构函数执行!" << endl; }
};

void myPrint2(const int i, const A &buf)
{
	cout << "引用的对象地址是"<< &buf << endl;
	return;
}
int main()
{
	//1.传递临时对象作为线程参数
	//1.1要避免的陷阱
	//int marv = 1;
	//int &marvy = marv;

	//char buf[] = "Hello child";

	thread thread1(myPrint, marv, buf);
	//thread thread1(myPrint, marv, string(buf));
	buf是什么时候转换成string
	事实上存在,buf被回收了(main函数执行结束),buf才转换成string的可能性
	稳妥的做法:buf先转换成sring,在传递
	//thread1.detach();

	int marv = 1;
	int mySecondPar = 10;
	//thread thread2(myPrint2, marv, mySecondPar);
	//语法上没有错误,mySecondPar隐式转换成A类型对象,传递给myPrin2的第二个参数.
	//但是临时对象创建的时间不确定
	thread thread2(myPrint2, marv, A(mySecondPar));
	//显式类类型转换,thread启动时就创建临时对象
	thread2.detach();

	cout << "main thread" << endl;
	
	return 0;

1.如果传递int这种简单类型,推荐使用值传递,不要用引用
2.如果传递类对象,避免使用隐式类型转换,全部都是创建线程这一行就创建出临时对象,(这样会调用构造函数两次)然后在函数参数里,用引用来接,否则还会创建出一个对象(不用引用,会调用构造函数三次,造成浪费)
3.终极结论:建议不使用detach
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值