Below is an example quoted from C++ Concurrency in Action $2.2
void f(int i,std::string const& s);
void oops(int some_param)
{
char buffer[1024];
sprintf(buffer, "%i",some_param);
std::thread t(f,3,buffer);
t.detach();
}
And the author says it's undefined behavior:
In this case, it’s the pointer to the local variable
buffer
that’s passed through to the new thread, and there’s a significant chance that the function oops will exit before the buffer has been converted to astd::string
on the new thread, thus leading to undefined behavior. The solution is to cast tostd::string
before passing the buffer to the std::thread constructor:
void f(int i,std::string const& s);
void not_oops(int some_param)
{
char buffer[1024];
sprintf(buffer,"%i",some_param);
std::thread t(f,3,std::string(buffer));
t.detach();
}
But I'm confused about that. Because as far as I'm concernd, there's no difference between the two forms:
In the first code snippet,when passing buffer
to the function as parameter,it will also generate a temporary std::string
object,and bind function parameter to that temporary object.So it's exactly the same with the second code snippet.The only difference is that temporary object in former one is generated by compiler implicitly and latter one by user explicitly.