The lambda expression exists to simplify code. This:
auto fun = []() { return; };
Is replaced by the compiler with:
// Namespace scope
struct __lambda_1 {
void operator()() { return; }
};
// local scope
__lambda_1 fun{};
This is the primary motivation for the lambda syntax: To replace traditional function objects with an easier to read anonymous function declared at the site where it is needed, rather than having a separate function object that must be declared in another scope. It is not merely to replace named function objects.
Indeed, the standard library includes a number of named function objects like std::unary_function
and things like std::less
. But these objects have limited utility and cannot take on every potential role that a lambda would.
So, yes, it can make code substantially more readable, by placing code that the standard library doesn't provide precisely where it's required, without polluting your code with dozen-line struct
s and polluting your namespace with names you'll likely use no more than once or twice.