C++ 多线程-作为参数传递的常量字符数组
我的职能如下:C++ 多线程-作为参数传递的常量字符数组,c++,multithreading,boost,C++,Multithreading,Boost,我的职能如下: laodFunc(const map<uint16_t, string> & pClasses, const char * pFilePath); 但是当我在被调用的方法中显示给定的路径(char*)时,我得到了一个错误的内容: 路径 我想知道我做错了什么。 感谢myStr.str().c_str()引用的内存被立即销毁(因为由myStr.str()返回的临时std::string被销毁),因此线程正在取消对悬挂指针的引用(导致未定义的行为) 要更正,请确保
laodFunc(const map<uint16_t, string> & pClasses, const char * pFilePath);
但是当我在被调用的方法中显示给定的路径(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());
由于
myStr
是一个由多个线程使用的全局变量(因此您可以获得“变量的最新设置”的值),或者是一个在使用后“消失”的局部变量,因此您需要采取一些措施使其持久化,并且每个线程都是唯一的。这里不完全清楚您的目的是什么,但是“每个线程”对象,该对象保存与线程一起创建的字符串,并在线程被销毁时被销毁。根据未显示的流,情况不一定如此,但我打赌你是对的!@MartinJames,但是std::string
立即被销毁。stringstream
的生存期是不可恢复的埃万特。
loadFunc(const map<uint16_t, string> & pClasses, std::string const& pFilePath);
boost::thread *new_thread = new boost::thread(&loadFunc, classes, myStr.str());
boost::thread *new_thread = new boost::thread(&loadFunc,
boost::cref(classes),
myStr.str());