zoukankan      html  css  js  c++  java
  • void operator()()的功能

    在学习多线程的时候看到这样的一段代码,为什么要重载()呢?真有这个必要吗?

    #include <iostream>
    #include <thread>
    
    class Counter {
    public:
      Counter(int value) : value_(value) {
      }
    
      void operator()() {
        while (value_ > 0) {
          std::cout << value_ << " ";
          --value_;
          std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        std::cout << std::endl;
      }
    
    private:
      int value_;
    };
    
    int main() {
      std::thread t1(Counter(3));
      t1.join();
    
      std::thread t2(Counter(3));
      t2.detach();
    
      // 等待几秒,不然 t2 根本没机会执行。
      std::this_thread::sleep_for(std::chrono::seconds(4));
      
      return 0;
    }
    
    

    对 void operator()()的功能表示困惑

    // 查阅了一些资料,这个是简易的说明代码
    class background_task
    {
    public:
        void operator()() const
        {
            do_something();
            do_something_else();
        }
    };
    background_task f;
    std::thread my_thread(f);
    

    在这里,为什么我们需要operator()()?第一个和第二个()的意思是什么?其实我知道这是重载运算符的操作()

    我们在学习C++的时候,学习过运算符重载。这里重载() 可以使对象像函数那样使用,常常被称为函数对象。 (这里用作线程对象的构造)

    第一个()是运算符的名称 – 它是在对象上使用()时调用的运算符. 第二个()是用于参数的。
    以下是您如何使用它的示例:

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

    有参数的演示:

    #include <iostream>
    
    class Test {
    public:
        void operator()(int a, int b) {
            std::cout << a + b << std::endl;
        }
    };
    
    int main() {
        Test t;
        t(3,5);
        return 0;
    }
    
    // 输出结果
    // 8
    
  • 相关阅读:
    Spring Boot 学习随记
    Prometheus 普罗米修斯监控
    安装VC++6.0步骤及心得
    NFS 系统搭建
    Centos 搭建邮箱系统
    搭建 RTMP 服务器
    阿里云 DTS 实践
    ELK 搭建
    Prometheus 和 Grafana 安装部署
    Centos7 Nagios 搭建
  • 原文地址:https://www.cnblogs.com/__tudou__/p/11297325.html
Copyright © 2011-2022 走看看