Problem
class background_task{public: voidconst { do_something(); do_something_else(); }};std::thread my_thread(background_task());my_thread.join();
Compile prompt Error:
Request for member ' join ' in ' My_thread ', which is of Non-class type ' Std::thread (Background_task (*) ()) '
My_thread.join ();
Reason
When a function object is passed into the thread constructor, if you pass a temporary function object instead of a named function object, the C + + compiler resolves it to a function declaration instead of defining an anonymous object. This is the problem caused by the C + + 's most vexing parse.
That is, the compiler resolves the 10th line of code above to: declares a function named My_thread, whose return type is Std::thread, the parameter is a function pointer, the function pointer to the function whose return type is Background_task, and the argument is void. That is, the type of My_thread is prompted by the compiler: Std::thread (Background_task (*) ()), of course, no member function joins.
Solutions
- Using Named Function objects
background_task f;std::thread my_thread(f);
- Use multiple sets of parentheses
std::thread my_thread((background_task()));
- Using the new unified initialization syntax
std::thread my_thread{background_task()};
- Using lambda expressions
std::thread my_thread([]{ do_something(); do_something_else();});
Summarize
- The problems encountered above can be extended to all objects that receive an anonymous function object as a constructor parameter.
Reference Link 1
Reference Link 2
The thread object is not a class type when you use the thread class's join method in c++11