创建临时对象为线程参数
用detach时,子线程引用主函数中的参数会引发很多问题,例如:变量还没有复制到子线程中就已经被收回。
- 若传递int这种简单类型参数,建议是值传递,必要用引用和指针,避免界外生枝。
- 如果传递类对象,避免隐式类型转换。全部在创建线程这一行构建出临时对象来,然后在函数参数里,用引用来接,否者会多构造一次对象。
建议不适用detach(),只使用join():这样就不会出现局部变量失效导致的线程对非法内存的引用。
#include<iostream>
#include<thread>
using namespace std;
class A
{
public:
int a;
A(int ai) :a(ai)
{
cout << "我是构造函数" << "线程id:" << std::this_thread::get_id() << endl;
}
A(const A &a)
{
cout << "我是拷贝构造函数" << "线程id:" << std::this_thread::get_id() << endl;
}
~A()
{
cout << "我是析构函数" << "线程id:" << std::this_thread::get_id() << endl;
}
};
void myfunc(int i,A &a)//用引用接
{
cout << "myfunc函数执行" << "线程id:" <<