Suppose we got this code:
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;
}
This program won't execute properly and I really want to know what is the reason behind it. As far as I'm concered, std::thread objects copies the arguments we sent them. Here's what I think happened:
field
gets converted to char*
(temporary object) and std::thread
object copies that char*
object. Meanwhile we have detached our thread and the function finishes. The function deletes its local variables (so char field[]
no longer exists) and so our char*
iniside our std::thread
object holds invalid address therefore we cannot convert that char*
into temporary std::string
in order to bind const std::string
reference to it.
Am I right ? What am I missing ? Also, does the same explanation applies if the function's signature was void err(std::string const field)
(no reference now) ?
By the way, I know the solution to this would be std::thread t1(err, std::string(field));
.