线程函数中的c++参数更改
c++ argument changes in thread function
我正在编写一个Android应用程序,它读取c++(NDK(中的文本文件。
我将文件list
从assets
文件夹复制到/data/user/0/my-package/files/list
,在那里我可以用我的本地代码读取,复制完成后或如果目标文件存在,我会执行以下操作:
const char* fileName = env->GetStringUTFChars(_name, nullptr);
const char* filePath = env->GetStringUTFChars(_destination, nullptr);
if(copy_file(AAssetManager_fromJava(env, manager),fileName, filePath)){
Reader *r = new Reader();
log("Initializing reader with file: %s",filePath);
thread t(&Reader::read, r, filePath);
t.detach();// will crash if no detach, join() will block the UI thread.
}
我的Reader::read
:
void Reader::read(const char* filePath){
log("Reading from file: %s",filePath);
ifstream infile(filePath);
string line;
while(infile>>line){
// read logic ...
}
}
我得到不同的输出,有时
Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files/list
一切都按预期进行但是有时我会收到
Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files
看到了吗?文件路径似乎被切断了,我的ifstream
正在尝试读取目录files
。
我被告知,默认情况下,参数filePath
将按值传递给线程,并且没有其他线程使用该变量,线程初始化后filePath
发生的唯一情况是:
env->ReleaseStringUTFChars(_destination, filePath);
我已经尝试了许多不同的方法来将文件路径传递给新线程,如果我像这样传递filePath
std::ref(filePath)
,我会在read
函数中得到空字符串,因为变量已经在外部清除。
对此有什么建议吗?
在线程完成之前调用ReleaseStringUTFChars将是灾难性的,因为filePath指向的内存也将被释放。如果您不完全理解指针和内存处理是如何工作的,我建议使用类似于std::string的东西,而不是constchar*,并将该字符串传递给您的函数。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用