c++ - 本例中圆括号“()”重载是什么意思

标签 c++ multithreading operator-overloading

我是 C++ 的菜鸟。我学习了一个简单的例子(见下面的代码)。我无法理解重载“()”的目的是什么。 std::thread my_thread(my_func);中使用的是“重载()”吗?

感谢大家的关注。

struct func
{
 int& i;
 func(int& i_) : i(i_) {}
 **void operator() ()** // the question point
 {
 for (unsigned j=0 ; j<1000000 ; ++j)
 {
   do_something(i);           
 }
}
};
void oops()
{
 int some_local_state=0;
 func my_func(some_local_state);
 std::thread my_thread(my_func);
 my_thread.detach();          
 } 

最佳答案

用你的func my_func(some_local_state);, 你现在可以像这样调用 my_func();
是一个函数(而不是类似 my_func.dosomething(); 的东西),并且循环在
运算符函数将被执行。

std::thread 以这种方式使用它(无论出于何种原因,创建者只是喜欢它)。
因此,如果没有 operator(),您的对象对 std::thread

没有任何意义

关于c++ - 本例中圆括号“()”重载是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966801/

相关文章:

Java并发实践Listing10.6 synchronized

c++ - 我在实现++ 增量运算符时遇到问题

c++ - 关于重载 "="以及我是否可以避免它

c++ - 对维基百科的 HTTP 请求

c++ - 关于STL容器

c++ - C++ 中的模板语法

c++ - 链接器错误 : already defined in my project when I don't define it at all

java - Android/Java - 暂停线程

multithreading - C++ 11 多线程归并排序

ruby-on-rails - 如何重载 Ruby 中的 << 运算符?