临时对象作为线程参数构造时机捕抓

范例一:

#include <iostream>
#include <thread>
using namespace std;

class A
{
    
    
public:
	A(int a) :m_i(a)
	{
    
    
		std::cout << "构造函数执行了" << "this= " << this << "线程ID:"<< std::this_thread::get_id()<< std::endl;
	}
	A(const A& a)
	{
    
    
		std::cout << "拷贝构造函数执行了" << "this= " << this  << "线程ID:" << std::this_thread::get_id() <<std::endl;
	}
	~A()
	{
    
    
		std::cout << "析构函数执行了" << "this= " << this << "线程ID:" << std::this_thread::get_id() << std::endl;
	}
	int m_i;
};

void func(int i, const A& buf)
{
    
    
	//std::cout << i << std::endl;
	std::cout << &buf << std::endl;
	std::cout << "子线程ID:"<< std::this_thread::get_id() << std::endl;
}

int main()
{
    
    
	int a = 1;
	//A senvar = 2;
	std::thread mthread(func, a, a);
	std::cout << "主线程ID:" << std::this_thread::get_id() << std::endl;
	mthread.join();
	//mthread.detach();
}

在这里插入图片描述

从结果可以看出在子线程中的第二个参数是在子线程当中构造的,如果主线程执行结束了,那么a将被系统回收,这个时候如果用detach就会存在隐患。

范例二:

#include <iostream>
#include <thread>
using namespace std;

class A
{
    
    
public:
	A(int a) :m_i(a)
	{
    
    
		std::cout << "构造函数执行了" << "this= " << this << "线程ID:"<< std::this_thread::get_id()<< std::endl;
	}
	A(const A& a)
	{
    
    
		std::cout << "拷贝构造函数执行了" << "this= " << this  << "线程ID:" << std::this_thread::get_id() <<std::endl;
	}
	~A()
	{
    
    
		std::cout << "析构函数执行了" << "this= " << this << "线程ID:" << std::this_thread::get_id() << std::endl;
	}
	int m_i;
};

void func(int i, const A& buf)
{
    
    
	//std::cout << i << std::endl;
	std::cout << &buf << std::endl;
	std::cout << "子线程ID:"<< std::this_thread::get_id() << std::endl;
}

int main()
{
    
    
	int a = 1;
	//A senvar = 2;
	std::thread mthread(func, a, A(a));
	std::cout << "主线程ID:" << std::this_thread::get_id() << std::endl;
	mthread.join();
	//mthread.detach();
}

在这里插入图片描述
使用了A(a)以后在子线程当中使用的buf对象是在主线程当中通过拷贝构造函数构造的,所以即使使用detach也不用担心主线程执行结束,子线程使用的对象还没构造完毕了。

范例三:

#include <iostream>
#include <thread>
using namespace std;


class A
{
    
    
public:
	A(int a) :m_i(a)
	{
    
    
		std::cout << "构造函数执行了" << "this= " << this << "线程ID:"<< std::this_thread::get_id()<< std::endl;
	}
	A(const A& a)
	{
    
    
		std::cout << "拷贝构造函数执行了" << "this= " << this  << "线程ID:" << std::this_thread::get_id() <<std::endl;
	}
	~A()
	{
    
    
		std::cout << "析构函数执行了" << "this= " << this << "线程ID:" << std::this_thread::get_id() << std::endl;
	}
	int m_i;
};

void func(int i, const A buf)
{
    
    
	//std::cout << i << std::endl;
	std::cout << &buf << std::endl;
	std::cout << "子线程ID:"<< std::this_thread::get_id() << std::endl;
}

int main()
{
    
    
	int a = 1;
	//A senvar = 2;
	std::thread mthread(func, a, A(a));
	std::cout << "主线程ID:" << std::this_thread::get_id() << std::endl;
	mthread.join();
	//mthread.detach();
}

在这里插入图片描述
如果不用引用的话,会多调用一次拷贝构造函数,而且buf变量是在子线程当中才构造的。

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/120119915