C++thread detachの大きな穴

3463 ワード

サンプルコード:
void testDetachThread(const string &str,int num)
{
	for (int i=0;i<num;i++)
	{
		cout <<i<<" "<<"id:"<<this_thread::get_id()<<"  "<< str << endl;
	}
}

int main()
{
	string str = "shen";
	//const char* data = str.c_str();
	thread detach_thread(testDetachThread, str.c_str(), 5);
	detach_thread.detach();
}


このコードは、main関数の実行が完了するとstrが解放されてtestDetachThreadという関数が実行され、長い間不正なポインタにアクセスする可能性があります.
  • テンポラリオブジェクトを構築するプライマリスレッドは、必ずサブスレッドに渡されるテンポラリオブジェクトを構築します.

  • ソリューション:
    thread detach_thread(testDetachThread, string(data), 5);
    

    以上のコードはjoinで問題はありません.メインスレッドはサブスレッドの実行が完了してから実行を続行するのを待つからです.