首页 > 解决方案 > 向 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));.

标签: c++multithreadingimplicit-conversion

解决方案


推荐阅读