class MyClass
{
public:
int _a;
MyClass(){
_a = 0;
};
~MyClass(){
_a = -1 ;
};
MyClass(const MyClass& my){
_a = 2;
}
};
void ThreadTest::Async()
{
MyClass a;
a._a = 10;
auto t = std::thread(&ThreadTest::run, this, a);
t.detach();
}
void ThreadTest::run(const MyClass &arg)
{
while(true){
int b =arg._a;
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);
}
}
写代码的时候,担心std::thread传递引用时,会出现局部变量先被释放的情况。写了个测试代码跟一下流程。C++源码不想看,太多范式了和宏定义了,害怕。
言归正传,std::thread调用时,实际是进行了两次拷贝的。所以线程中访问的arg,已经不是a了,是经过拷贝过的新对象。所以b的值为2.
因此可以不用太担心局部变量被释放的情况。