Avoid memory allocation with std::function and member function

前端 未结 5 1446
野的像风
野的像风 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:14

    Unfortunately, allocators for std::function has been dropped in C++17.

    Now the accepted solution to avoid dynamic allocations inside std::function is to use lambdas instead of std::bind. That does work, at least in GCC - it has enough static space to store the lambda in your case, but not enough space to store the binder object.

    std::function func = [&cb]{ cb.Fire(); };
        // sizeof lambda is sizeof(MyCallBack*), which is small enough
    

    As a general rule, with most implementations, and with a lambda which captures only a single pointer (or a reference), you will avoid dynamic allocations inside std::function with this technique (it is also generally better approach as other answer suggests).

    Keep in mind, for that to work you need guarantee that this lambda will outlive the std::function. Obviously, it is not always possible, and sometime you have to capture state by (large) copy. If that happens, there is no way currently to eliminate dynamic allocations in functions, other than tinker with STL yourself (obviously, not recommended in general case, but could be done in some specific cases).

提交回复
热议问题