Avoid memory allocation with std::function and member function

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

This code is just for illustrating the question.

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

int main()
{
    MyCallBack cb;
             


        
5条回答
  •  不知归路
    2021-01-31 17:18

    As an addendum to the already existent and correct answer, consider the following:

    MyCallBack cb;
    std::cerr << sizeof(std::bind(&MyCallBack::Fire, &cb)) << "\n";
    auto a = [&] { cb.Fire(); };
    std::cerr << sizeof(a);
    

    This program prints 24 and 8 for me, with both gcc and clang. I don't exactly know what bind is doing here (my understanding is that it's a fantastically complicated beast), but as you can see, it's almost absurdly inefficient here compared to a lambda.

    As it happens, std::function is guaranteed to not allocate if constructed from a function pointer, which is also one word in size. So constructing a std::function from this kind of lambda, which only needs to capture a pointer to an object and should also be one word, should in practice never allocate.

提交回复
热议问题