今天想到一个问题:如果用类成员函数作为线程函数,那么当线程还在执行的过程中,这个类对象析构了会怎么样。动手写个小程序试试,毕竟实践是检验真理的唯一标准么。
#include <iostream>
#include <thread>
class ThreadTest
{
public:
int i;
void Process()
{
i = 0;
while (true)
{
std::cout << i++ << std::endl;
Sleep(1000);
}
}
};
int main()
{
ThreadTest* test = new ThreadTest();
std::thread thr(&ThreadTest::Process, test);
Sleep(5000);
test->i = 100;
Sleep(5000);
delete test;
getchar();
}
运行结果如下:-572662304这个会一直打印,除非主程序退出。

就是这么回事,两个线程公用一个对象,所以在使用类对象时要时刻注意数据安全。