c++ - 向 std::thread 对象发送参数
问题描述
假设我们得到了这段代码:
void err(std::string const& field){
for(int i=0; i<field.size(); ++i)
std::cout << field[i] << " ";
std::cout << std::endl;
}
void test() {
char field[]= "abcdef";
std::thread t1(err, field); ///problem
t1.detach();
}
int main(){
test();
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
该程序无法正常执行,我真的很想知道它背后的原因。据我所知,std::thread 对象复制了我们发送给它们的参数。这是我认为发生的事情:
field
被转换为char*
(临时对象)并且std::thread
对象复制该char*
对象。同时我们已经分离了我们的线程并且函数完成了。该函数删除了它的局部变量(因此char field[]
不再存在),因此我们char*
的std::thread
对象内部持有无效地址,因此我们无法将其转换char*
为临时地址std::string
以绑定const std::string
对它的引用。
我对吗 ?我错过了什么?此外,如果函数的签名是void err(std::string const field)
(现在没有参考),是否也适用相同的解释?
顺便说一句,我知道解决方案是std::thread t1(err, std::string(field));
.
解决方案
推荐阅读
- node.js - 每次我运行 gulp 或 gulp build local 我都会得到 AssertionError [ERR_ASSERTION]: Task never defined: build
- sql - 当给定每个科目的单独分数时,查找每个班级的最佳名单
- xamarin.android - 以编程方式设置包含 android:textColor 和 android:background 的样式?(Xamarin.Android)
- mockito - java.lang.NoClassDefFoundError: org/junit/platform/commons/PreconditionViolationException 尝试使用 maven 运行 mockito junit5 测试
- angular - 角度 HttpClient 调用在 IE 中不起作用?
- javascript - Google Apps 脚本找不到已创建的广告系列
- python - 如何将结果 .json 文件保存到 IBM Cloud Storage?
- python - 使用 path.open('r', encoding="utf-8") 作为文件:AttributeError: 'generator' object has no attribute 'open'
- fortran - 在 Fortran 格式中使用双反斜杠
- reactjs - 在 _app.js (nextjs) 中接收新道具?