2013-07-03 86 views
1

我有一个函数如下:多线程 - 为const char数组传递作为参数

laodFunc(const map<uint16_t, string> & pClasses, const char * pFilePath); 

而且我通过这种方式调用它。 ,为了运行与升压

boost::thread_group g; 
stringstream myStr; 
...... 
boost::thread *new_thread = new boost::thread(&loadFunc,classes,myStr.str().c_str()); 
g.add_thread(new_thread); 

一个新的线程但是,当我在调用的方法显示给定的路径(字符*)我得到一个错误的内容: 路径?

我想知道的请我在做什么错在这里。 由于

回答

3

存储器通过myStr.str().c_str()称为被immedately破坏(因为由myStr.str()返回的临时std::string被破坏),所以该线程被解除引用悬空指针(导致未定义的行为)。

要纠正,确保提供给laodFunc()指针仍然有效线程的生命周期。或者,改变const char* pFilePathstd::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.str()将被保存并传递给线程函数(见Thread Constructor with arguments)。它是一文不值的classes说法也将被复制,即使参数类型的loadFunc()const&。如果需要,这个副本可以通过使用boost::cref()来避免:

boost::thread *new_thread = new boost::thread(&loadFunc, 
               boost::cref(classes), 
               myStr.str()); 
+0

这不一定的情况下,根据未显示的流量,但我敢打赌,你说得对! –

+2

@MartinJames,b立即销毁'std :: string'。 'stringstream'的生命周期是无关紧要的。 – hmjd

+0

@hmjd谢谢你的回答 – saloua

0

由于myStr或者是由多个线程使用的全局变量(所以你得到了“可变的最新设置”的值,或一个局部变量即“消失”使用后,你需要做一些事情,使之持续,是每个线程是唯一的。它不是完全清楚在这里你的目的是什么,但“每线程”对象包含字符串,与一起创建线程,当线程被销毁工作将被销毁。