std::thread 传参时候的一些坑
#include <thread>
void mufunc1(const int &i, char *pbuf){}//此时i并不是传递的引用,而是复制值,所以thread detach 时候没有问题;但pbuf是传递的指针,所以thread detach时候会有问题
void mufunc2(const int i, const string& pbuf){}
int main()
{
int nVal = 1;
int &nValy = nVal;
char myBuf[] = "i love c++";
std::thread th(myfunc1, nVal, myBuf); //---error
std::thread th(myfunc2, nVal, string(myBuf)); //myBuf在强制转换的时候, 会先复制一份临时变量,所以myBuf局部析构时候,thread中仍然可以使用数据 -- ok
}
本文探讨了在C++中使用std::thread进行函数调用时,参数传递的细节。通过示例展示了值传递可能导致的数据不一致问题,以及引用传递可能遇到的问题。特别地,当传递指针时,在线程detach后,原始指针对象可能已销毁,导致线程访问无效内存。同时,介绍了如何通过复制字符串来避免这类问题。
8824

被折叠的 条评论
为什么被折叠?



