多线程-作为参数传递的常量字符数组
Multithreading - const char array passed as parameter
我有一个函数如下:
laodFunc(const map<uint16_t, string> & pClasses, const char * pFilePath);
我这样称呼它。为了将其作为一个新线程与boost 一起运行
boost::thread_group g;
stringstream myStr;
......
boost::thread *new_thread = new boost::thread(&loadFunc,classes,myStr.str().c_str());
g.add_thread(new_thread);
但是当我在调用的方法中显示给定的路径(char*)时,我得到了错误的内容:路径
我想知道我在这里做错了什么。感谢
myStr.str().c_str()
引用的内存被立即销毁(因为myStr.str()
返回的临时std::string
被销毁),因此线程正在取消对悬挂指针的引用(导致未定义的行为)。
要进行更正,请确保提供给laodFunc()
的指针在线程的生存期内保持有效。或者,将const char* pFilePath
更改为std::string const& pFilePath
:
loadFunc(const map<uint16_t, string> & pClasses, std::string const& pFilePath);
boost::thread *new_thread = new boost::thread(&loadFunc, classes, myStr.str());
CCD_ 7的副本将存储在内部并传递给线程函数(请参阅带参数的线程构造函数)。即使loadFunc()
的参数类型是const&
,classes
参数也将被复制,这毫无意义。如果需要,可以使用boost::cref()
:来避免此副本
boost::thread *new_thread = new boost::thread(&loadFunc,
boost::cref(classes),
myStr.str());
由于myStr
要么是多个线程使用的全局变量(因此您可以获得"变量的最新设置"的值),要么是使用后"消失"的局部变量,因此您需要采取措施使其持久化并在每个线程中唯一。这里不完全清楚您的目的是什么,而是"每个线程"对象,该对象包含与线程一起创建的字符串,并在线程被销毁时被销毁。
相关文章:
- 如何循环访问常量字符**?
- constexpr 函数获取常量字符*
- 如何计算常量字符**中的总字符数?
- QDial:如何将 int 值传递给需要常量字符*的 Qfile?
- 为什么 std::string_view 比常量字符*快?
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 在编译时将常量字符* 转换为常量 char_type*
- 将字符串数组传递给接受常量字符**的函数
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 字符串强制转换为常量字符*
- 使用常量字符*时退出代码 139
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法<string>从"常量字符 []"转换为<类名>
- 初始化常量字符* 数组
- 常量字符*的性质是什么?
- C++ 获取向量中常量字符* [ ] 的长度
- 无法将参数 1 从 WCHAR 转换为常量字符 *
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- C++将常量字符* 指针数组传递给对象