Search code examples
multithreadingc++11syntaxmost-vexing-parse

why should the functor be placed inside the brackets while passing to thread costructor?


#include <iostream>
#include <thread>
class DisplayThread
{
public:
    void operator()()     
    {
        for(int i = 0; i < 10000; i++)
            std::cout<<"Display Thread Executing"<<std::endl;
    }
};
 
int main()  
{
   //line 1:
    std::thread threadObj( (DisplayThread()) );
    for(int i = 0; i < 10000; i++)
        std::cout<<"Display From Main Thread "<<std::endl;
    std::cout<<"Waiting For Thread to complete"<<std::endl;
    threadObj.join();
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}
    

In line 1: if i use like "threadObj(DisplayThread())", It gives an error saying no class type.

Could someone tell me why functor while passing to thread constructor has to be inside"()" braces?


Solution

  • Congratulations... of sorts: You have fallen victim to the C++ phenomenon known as the Most Vexing Parse: Basically, a tendency of the compiler to interpret your statements as function declarations. You are not at fault - it's the result of ambiguity in the language which happens to be resolved in a somewhat unintuitive way.

    The error you get when you remove the parentheses around DisplayThread() is:

    <source>: In function 'int main()':
    
    <source>:20:15: error: request for member 'join' in 'threadObj', which is of 
    non-class type 'std::thread(DisplayThread (*)())'
       20 |     threadObj.join();
          |               ^~~~
    

    The compiler thinks threadObj is a function, which takes a function pointer and returns an std::thread!

    This is resolved if you use curly-braces for no-argument construction, like so:

    std::thread threadObj{ DisplayThread{} };