The thread object is not a class type when you use the thread class's join method in c++11

Source: Internet
Author: User
Tags thread class

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
    1. Using Named Function objects
background_task f;std::thread my_thread(f);
    1. Use multiple sets of parentheses
std::thread my_thread((background_task()));
    1. Using the new unified initialization syntax
std::thread my_thread{background_task()};
    1. Using lambda expressions
std::thread my_thread([]{    do_something();    do_something_else();});
Summarize
    1. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.