简体   繁体   English

构造线程时调用的运算符重载函数

[英]operator overloading function called when constructing a thread

Lately, I came across with this code as part of studying threading , and there is a part which I can't understand. 最近,我在学习线程过程中遇到了这段代码,其中有些是我无法理解的。
here is the code: 这是代码:

#include <iostream>
#include <thread>

void foo() { std::cout << "foo()\n"; }
void bar() { std::cout << "bar()\n"; }

class task
{
 public:
     task() { cout << "task constructor\n"; }

     void operator()() const
     {
        cout << "operator()\n";
        foo();
        bar();
     }
};

int main()
{
   task tsk;
   std::thread t(tsk);
   t.join();
   return 0;
}

the part I didn't understand was after creating "tsk" object. 我不了解的部分是在创建“ tsk”对象之后。 when constructing the "t" thread std::thread t(tsk); 构造“ t”线程时std::thread t(tsk);
the operator overload function was called . 运算符重载函数被调用
I didn't understand why the operator overloading "()" was called and when this happened. 我不明白为什么调用运算符重载“()”以及何时发生这种情况。
I will be really greatful if anyone can explain me this stuff. 如果有人可以向我解释这些内容,我将非常感激。

std::thread takes a callable object to execute. std::thread需要一个可调用对象来执行。 When you overload operator()() , you are making your task object callable. 当重载operator()() ,就使您的task对象可调用。

Example: 例:

tsk();
// Output
task constructor
operator()
foo()
bar()

Remove your definition of operator()() ... 删除您对operator()()定义...

tsk();
// Output
error: type 'task' does not provide a call operator

std::thread t(tsk); won't even compile unless task is a callable object. 除非task是一个可调用对象,否则甚至都不会编译。

If you're asking why it behaves this way, we take a look to n3376 (C++11 draft standard) [thread.thread.constr]. 如果您要问为什么它会以这种方式运行,我们来看看n3376 (C ++ 11草案标准)[thread.thread.constr]。 The constructor std::thread t(tsk); 构造函数std::thread t(tsk); is calling is: 正在调用的是:

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

This constructor executes INVOKE(DECAY_COPY( std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...) . 此构造函数执行INVOKE(DECAY_COPY( std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...) In other words, it calls f(arg1, arg2, arg3...) . 换句话说,它调用f(arg1, arg2, arg3...)

If you want unofficial documentation that says it better than I do, try cppreference . 如果您想要比我说得更好的非官方文档,请尝试使用cppreference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM