构造线程时调用的操作符重载函数
operator overloading function called when constructing a thread
最近,我偶然发现这段代码是学习线程的一部分,其中有一部分我不明白。
下面是代码:
#include <iostream>
#include <thread>
void foo() { std::cout << "foo()n"; }
void bar() { std::cout << "bar()n"; }
class task
{
public:
task() { cout << "task constructorn"; }
void operator()() const
{
cout << "operator()n";
foo();
bar();
}
};
int main()
{
task tsk;
std::thread t(tsk);
t.join();
return 0;
}
我不理解的部分是在创建"task"对象之后。当构造"t"线程std::thread t(tsk);
时操作符重载函数调用。
我不明白为什么操作符重载"()"被调用,以及何时发生。
std::thread
接受一个可调用对象来执行。当你重载operator()()
时,你使你的task
对象可调用。
的例子:
tsk();
// Output
task constructor
operator()
foo()
bar()
删除operator()()
…
tsk();
// Output
error: type 'task' does not provide a call operator
std::thread t(tsk);
甚至不会编译,除非task
是一个可调用的对象。
如果你问为什么这样做,我们看一下n3376 (c++ 11草案标准)[thread.thread.constr]。std::thread t(tsk);
调用的构造函数是:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
这个构造函数执行INVOKE(DECAY_COPY( std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...)
。换句话说,它调用f(arg1, arg2, arg3...)
。
如果您想要比我说得更好的非官方文档,请尝试cppreference.