Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is C++ lambda implemented with functor instead of function pointer?

Tags:

c++

lambda

I found out that lambdas in both MSVC and GCC are functors implementing an operator(). What is the reason they prefer functor to function pointers?

like image 923
babel92 Avatar asked Dec 09 '13 17:12

babel92


3 Answers

The problem is that a lambda function in C++ can have an additional state (captured variables aka context) which has to be passed around for each instance (they can differ for each instance of the handle to the same lambda function).

A function cannot have a state coupled to the handle you pass around. If you would add such a state to a function pointer you end up writing a wrapper which needs to be callable using the parenthesis syntax (operator()) which happens to be what a functor is.

A notable fact is that a lambda without a capture can be converted to a function pointer. This is only possible because it does not require such additional space.

like image 104
leemes Avatar answered Nov 16 '22 23:11

leemes


Functions don't have state, so they wouldn't be able to implement the functionality required by lambdas.

Moreover, you are guaranteed that lambdas have a unique type, which you can't really do with functions alone.

like image 21
Kerrek SB Avatar answered Nov 16 '22 21:11

Kerrek SB


In addition to the already mentioned ability to capture, performance is also a reason. In general a function pointer can not be inlined. A functor can be. This is why std::sort is faster than qsort. As mentioned a lambda without captures can be turned into a function pointer, but this is mostly to interact with old c api's. i.e. so you can pass a lambda to an old win32 api function. In general for a simple lambda, the compiler would prefer to inline it instead.

like image 32
duhone Avatar answered Nov 16 '22 22:11

duhone