Are lambdas inlined like functions in C++?

c++, c++11, lambda, stl

Solution

First off: the whole point of the design of lambdas in C++ is that they don’t have an overhead compared to function calls. That notably includes the fact that calls to them can be inlined.

But there’s a confusion of concepts here: in the C++ standard, “inline” is a property of a function, i.e. it is a statement about how a function is defined, not how it gets called (in particular, it permits multiple identical definitions of the same name in multiple translation units). Functions that are defined inline can benefit from a compiler optimisation by which calls to such functions are inlined. It’s a different (though closely related concepts).

In the case of lambdas, the actual function being called is a member `operator()` that is implicitly defined as `inline` in an anonymous class created by the compiler for the lambda. Calls of the lambda are translated to direct calls to its `operator()` and can therefore be inlined. I’ve explained how the compiler creates lambda types in more detail in another answer.

Problem

Can/does the compiler inline lambda functions to increase efficiency, as it might with simple standard functions? e.g. ``` std::vector<double> vd; std::for_each(vd.begin(), vd.end(), [](const double d) {return d*d;}); ``` Or is there loss of efficiency caused by lack of optimisation? A second question: where I can check if the compiler I use has optimised calls of inline functions, which are sent to an algorithm? What I mean is, if a function—not a function object—is sent to an algorithm, the last one gets a pointer to the function, and some compilers optimize pointers to inline functions and others don't.

Original source

Related problems