What does the code actually do when I pass a mutable lambda as const reference?
Why does not the compiler raise error, is this an undefined operation?
Why f1 and f2 are differnt which f1 uses std::function<void()> and f2 uses auto?
I found a similar question but I still don't fully understand
A const std::function wraps a non-const operator() / mutable lambda
#include <iostream> #include <functional> void call(std::function<void()> const & cb) { cb(); cb(); } int main() { std::function<void()> f1 = [a = 0] () mutable { std::cout << ++a << std::endl; }; call(f1); // prints 1 2 call(f1); // prints 3 4 auto f2 = [a = 0] () mutable { std::cout << ++a << std::endl; }; call(f2); // prints 1 2 call(f2); // prints 1 2 }