void 运算符 ()() 的功能
Functionality of void operator()()
我对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)。
我希望我有所帮助。
- C++ - 没有自定义交换功能的移动分配运算符?
- C++语法运算符功能?
- 主功能外的新运算符 - C++
- 在功能块中使用新运算符时存在于堆或堆栈上?
- 预处理器是否可以更改运算符重载功能的符号?
- 插入运算符的过载与使用二传手功能相比
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 使用运算符读取文件和使用读取功能>>文件有什么区别?
- 使用赋值运算符功能按距离对数组对象进行排序
- C 超载相等运算符.我应该写自己的功能以接受通过参考或值传递的参数
- 在使用C 中使用多个三元运算符时,BOOL和ENUM类型超载的功能没有区分
- 如何通过运算符<<的重载访问受保护的功能?C++
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 错误 C2582:"运算符 ="功能不可用
- C++功能运算符结构不执行任何操作
- C 是否会用功能调用代替内置运算符
- 超载功能运算符
- 如何重载iostream运算符以在整个流上执行功能
- 优先级队列中的运算符重载或比较功能C++