2.1.1
One thing to note, when the function object passed to the constructor of the thread, it is necessary to avoid "the most vexing parsing" (C ++ 's most vexing parse, Chinese Introduction). If you pass a temporary variable instead of a variable named; C ++ compiler will parse function declaration, rather than defining the type of object .
For example:
std :: the Thread my_thread (background_task ()); //
Here is quite a statement with a function called my_thread of this function with a parameter (function has no parameters and returns a pointer to a function background_task object), function returns a std :: thread object, rather than start a thread. Use a named function object in front, or the use of multiple sets of brackets ①, or use the new unified initialization syntax ②, to avoid this problem. Using lambda expression can avoid this problem.
As follows:
STD :: Thread my_thread ((background_task ())); //. 1
std::thread my_thread{background_task()}; // 2
2.2
The default parameters to be copied to a separate thread in memory, even if the parameter is a reference to the form, and can be accessed in the new thread
void f(int i, std::string const& s);
std::thread t(f, 3, "hello");
char buffer[1024]; // 1
sprintf(buffer, "%i",some_param);
std::thread t(f,3,buffer); // 2
t.detach();
std::thread t(f,3,std::string(buffer));//使用std::string,避 免悬垂指针