This code is just for illustrating the question.
#include
struct MyCallBack {
void Fire() {
}
};
int main()
{
MyCallBack cb;
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.