定义线程传参结构体如下:
struct ThreadPara
{
std::string strNeName;
string strTime;
bool IsSuccess;
std::string strNeInst;
ThreadPara():strNeName(""),strTime(""),IsSuccess(false),strDesc(""),iphyINeid(0),strNeInst(""){}
};
在程序中创建线程跑函数体threadRun
ThreadPara *para = new ThreadPara1;
int iCreateResult=pthread_create(&ptid, NULL, (void*(*)(void*))threadRun, (void*)¶);
threadRun函数主要是经过一些处理给para结构体赋值,然而结构体的bool,int类型赋值时都正常,string赋值总是core。
经过多次测试后发现,需要将结构体中string类型转化为string * ,赋值时重新new出新对象来(new后,要记得delete)。程序才能正常处理。
猜测出现以上问题是因为string是对象而非内存,string赋值时会开辟新的地址,供string对象调用。而struct中 存储的是string对象地址,并且new结构体时只是new的string对象地址指针。它的指针存储在堆中,而对象变量存储在栈中,导致报错