I am confused about the functionality of void operator()()
.
Could you tell me about that, for instance:
class background_task
{
public:
void operator()() const
{
do_something();
do_something_else();
}
};
background_task f;
std::thread my_thread(f);
Here, why we need operator()()
? What is the meaning of the first and second ()
? Actually, I know the operation of normal operator, but this operator is confusing.
You can overload the
()
operator to call your object as if it was a function:So the first parentheses are always empty: this is the name of the function:
operator()
, the second parentheses might have parameters (as in my example), but they don't have to (as in your example).So to call this operator in your particular case you would do something like
task()
.The first part
operator()
is the way to declare the function that is called when an instance of the class is invoked as a function. The second pair of parentheses would contain the actual arguments.With a return value and arguments this might make a bit more sense:
In this context, the
std::thread
will internally invokef()
inside the thread, i.e. whatever is inside the body ofoperator()
is what gets done inside that thread.All the hints that were contributed above are correct to sequential programs, I mean, programs without threads. Using threads things change. First of all, by default parameters to std::thread are functions and functions parameters. Probably you were studying the book "C++ concurrency in action", and the author shows an interesting example:
Suppose this function:
void do_other_job(int k); In the body of the code, you should do:
in order to spawn another thread.
So, using threads the compiler interprets f ( in std::thread my_thread(f);) by default as a function instead of a class. To change that you have to initiate an operator() to warn the compiler you are working with a class. An alternative code could be:
Eventually, it's not correct, using threads, feeding the operator, so this code doesn't work:
It happens because all the code inside the brackets are read-only, and cannot be changed during the run-time. If you aim to insert a variable in the constructor, it must be put in the thread initialization. So:
Will run without mistakes, and will perform the function do_sth(12) in the thread spawned.
I hope I have helped.
The first
()
is the name of the operator - it's the operator that is invoked when you use()
on the object. The second()
is for the parameters, of which there are none.Here's an example of how you would use it: