我正在尝试运行以下简单示例。
void printString(const char* s)
{
std::cout << s << std::endl;
}
int main()
{
std::string str = "hello world";
std::thread T3(printString, str.c_str());
}
但是出现以下错误。
No matching constructor for initialization of 'std::thread'
我正在使用Xcode 11.1。
如果要进行编译,此代码甚至可以工作吗?由于线程共享相同的堆,因此线程T3
应该能够访问str.c_str()
对吗?假设在堆上分配了std::string
缓冲区。
谢谢!
为了使用std :: thread,您需要包含适当的头文件。然后,您必须决定等待线程完成其工作或分离它。否则,std :: thread将在析构函数中调用std :: terminate。另一个问题是,如果main返回并释放一个字符串,则在printString函数中将有一个悬空指针。
所以,一种可能的解决方案
#include <thread>
#include <iostream>
void printString(const char* s)
{
std::cout << s << std::endl;
}
int main()
{
std::string str = "hello world";
std::thread T3(printString, str.c_str());
T3.join();
return 0;
}