void 运算符 ()() 的功能

Functionality of void operator()()

本文关键字:功能 运算符 void      更新时间:2023-10-16

我对void operator()()的功能感到困惑。

你能告诉我吗,例如:

class background_task
{
public:
    void operator()() const
    {
        do_something();
        do_something_else();
    }
};
background_task f;
std::thread my_thread(f);

在这里,为什么我们需要operator()()?第一和第二()的含义是什么?实际上,我知道正常运算符的操作,但是这个运算符令人困惑。

您可以重载 () 运算符来调用您的对象,就好像它是一个函数一样:

class A {
public:
    void operator()(int x, int y) {
        // Do something
    }
};
A x;
x(5, 3); // at this point operator () gets called

所以第一个括号总是空的:这是函数的名称:operator(),第二个括号可能有参数(如我的示例),但它们不必(如您的示例)。

因此,要在特定情况下调用此运算符,您将执行类似 task() 的操作。

第一个()是运算符的名称 - 它是在对象上使用 () 时调用的运算符。第二个()是参数,其中没有参数。

下面是如何使用它的示例:

background_task task;
task();  // calls background_task::operator()

operator()的第一部分是声明当类的实例作为函数调用时调用的函数的方法。 第二对括号将包含实际参数。

使用返回值和参数,这可能更有意义:

class Adder{
public:
int operator()(int a, int b){
    //operator() -- this is the "name" of the operator
    //         in this case, it takes two integer arguments.
    return a+b;
}
};
Adder a;
assert( 5==a(2,3) );

在这种情况下,std::thread将在线程内部调用f(),即operator()体内的任何内容都是在该线程内完成的操作。

上面

提供的所有提示对于顺序程序都是正确的,我的意思是,没有线程的程序。使用线程会改变事情。首先,默认情况下 std::thread 的参数是函数和函数参数。可能您正在研究"C++并发在行动"一书,作者展示了一个有趣的例子:

void do_some_work(); 
thread my_thread(do_some_work); //thread receives the function address

假设此函数:

无效do_other_job(int k);在代码正文中,您应该执行以下操作:

k=3; 
thread my_thread2(do_other_job, k); 

为了生成另一个线程。

因此,使用线程,编译器默认将 f(在 std::thread my_thread(f);) 解释为函数而不是类。要更改它,您必须启动一个运算符()来警告编译器您正在使用一个类。替代代码可以是:

class background_task{
public: 
background_task(){
 do_sth(); 
 do_sth_else(); 
 }
void operator()(){} 
}; 
background_task f; 
thread mythread10(f);

最终,它不正确,使用线程,馈送运算符,因此此代码不起作用:

void operator()(int x){
do_sth(); 
cout<<"x = "<<x<<endl;
}

发生这种情况是因为括号内的所有代码都是只读的,并且在运行时无法更改。如果您打算在构造函数中插入变量,则必须将其放入线程初始化中。所以:

class backg{
public: 
backg(int i){
   do_sth(i); 
   }
void operator()(){}
}; 
int main(){
thread mythread{ backg(12) }; //using c++11
return 0; 
}

将运行而不会出错,并将在生成的线程中执行函数 do_sth(12)。

我希望我有所帮助。