Avoid memory allocation with std::function and member function

前端 未结 5 1435
野的像风
野的像风 2021-01-31 16:24

This code is just for illustrating the question.

#include 
struct MyCallBack {
    void Fire() {
    }
};

int main()
{
    MyCallBack cb;
             


        
5条回答
  •  萌比男神i
    2021-01-31 17:23

    Run this little hack and it probably will print the amount of bytes you can capture without allocating memory:

    #include 
    #include 
    #include 
    
    void h(std::function&& f, void* g)
    {
      f(g);
    }
    
    template
    void do_test()
    {
      size_t a[number_of_size_t];
      std::memset(a, 0, sizeof(a));
      a[0] = sizeof(a);
    
      std::function g = [a](void* ptr) {
        if (&a != ptr)
          std::cout << "malloc was called when capturing " << a[0] << " bytes." << std::endl;
        else
          std::cout << "No allocation took place when capturing " << a[0] << " bytes." << std::endl;
      };
    
      h(std::move(g), &g);
    }
    
    int main()
    {
      do_test<1>();
      do_test<2>();
      do_test<3>();
      do_test<4>();
    }
    

    With gcc version 8.3.0 this prints

    No allocation took place when capturing 8 bytes.
    No allocation took place when capturing 16 bytes.
    malloc was called when capturing 24 bytes.
    malloc was called when capturing 32 bytes.

提交回复
热议问题