将字符串指针传递给在C ++和Xcode 11.1中在不同线程上运行的函数

我正在尝试运行以下简单示例。

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缓冲区是在堆上分配的。

谢谢!

zudy2 回答:将字符串指针传递给在C ++和Xcode 11.1中在不同线程上运行的函数

要使用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;
}
,

我通过将CMake设置为使用C ++ 11来解决了这个问题

set (CMAKE_CXX_STANDARD 11)

现在,生成的Xcode项目已设置了正确的编译器标志,并且发布的代码可以正确编译。

本文链接:https://www.f2er.com/3148368.html

大家都在问