是std :: function比自动存储lambda函数更重要

Dan*_*Lee 5 c++ lambda auto c++11 std-function

我听说费用std::functionauto处理lambda函数要重.有效的现代c ++ item5.我想要的是澄清为什么std::function使用更多内存而不是auto一些示例代码的机制.有人能帮帮我吗?

编辑

class Widget {
public:
  Widget(int i) : i_(i) {}
  bool operator<(const Widget& o) { return o.value() > i_; }
  int value() const { return i_; };
private:
  int i_;
  int dummy_[1024];
};

int main() {
  // performance difference between auto and std::function
  { 
    auto less1 = [](const auto& p1, const auto& p2) {
      return *p1 < *p2;
    };
    std::cout << "size of less1: " << sizeof(less1) << endl;

    function<bool(const std::unique_ptr<Widget>&,
                  const std::unique_ptr<Widget>&)>
        less2 = [](const std::unique_ptr<Widget>& p1,
                   const std::unique_ptr<Widget>& p2) {
          return *p1 < *p2;
        };
    std::cout << "size of less2: " << sizeof(less2) << endl;

    {
      // auto
      std::vector<std::unique_ptr<Widget>> ws1;
      for (auto i = 0; i < 1024*100; ++i) {
        ws1.emplace_back(new Widget(std::rand()));
      }

      auto start = std::chrono::high_resolution_clock::now();
      std::sort(ws1.begin(), ws1.end(), less1);
      auto end = std::chrono::high_resolution_clock::now();
      cout << ws1[0].get()->value() << " time: " << (end - start).count() << endl;
    }

    {
      // std::function
      // 25% slower than using auto
      std::vector<std::unique_ptr<Widget>> ws2;
      for (auto i = 0; i < 1024*100; ++i) {
        ws2.emplace_back(new Widget(std::rand()));
      }

      auto start = std::chrono::high_resolution_clock::now();
      std::sort(ws2.begin(), ws2.end(), less2);
      auto end = std::chrono::high_resolution_clock::now();
      cout << ws2[0].get()->value() << " time: " << (end - start).count() << endl;
    }
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

它来自https://github.com/danielhongwoo/mec/blob/master/item5/item5.cpp

我认为这段代码显示我使用std::function的速度比使用auto慢.但不是使用内存.我只想用一些真实的代码来证明它.

Rei*_*ica 8

std::function可以存储任意可调用的.因此,必须进行类型擦除以能够存储任意类型的东西.这可能需要在一般情况下进行动态分配,并且它肯定需要在每次调用时进行间接调用(虚拟调用或通过函数指针调用)operator ().

lambda表达式的类型不是 std::function,它是一个带有已operator()定义的未命名类类型(lambda的闭包类型).使用auto a存储拉姆达使得类型a这种精确的闭合类型,它没有开销.