0

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));.

domdrag
  • 541
  • 1
  • 4
  • 13
  • 1
    This doesn’t address the question, but detaching threads is a bad habit to get into. There are a few situations where detaching is appropriate, but this is not one of them. – Pete Becker Oct 19 '20 at 19:23
  • You are right, and "no reference now" will still be undefined behavior. – Sam Varshavchik Oct 19 '20 at 19:28

0 Answers0