I\'ve been thinking about storing C++ lambda\'s lately. The standard advice you see on the Internet is to store the lambda in a std::function object. However, none of this adv
The standard advice you see on the Internet is to store the lambda in a std::function object. However, none of this advice ever considers the storage implications.
That's because it doesn't matter. You do not have access to the typename of the lambda. So while you can store it in its native type with auto
initially, it's not leaving that scope with that type. You can't return it as that type. You can only stick it in something else. And the only "something else" C++11 provides is std::function
.
So you have a choice: temporarily hold on to it with auto
, locked within that scope. Or stick it in a std::function
for long-term storage.
Is all this copying really necessary?
Technically? No, it is not necessary for what std::function
does.
Is there some way to coerce the compiler into generating better code?
No. This isn't your compiler's fault; that's just how this particular implementation of std::function
works. It could do less copying; it shouldn't have to copy more than twice (and depending on how the compiler generates the lambda, probably only once). But it does.