Why does the implicit "lambda for converting a function pointer" forbid "the capture of static members link?

In the C ++ 11 standard (or at least I have a version, not the latest):

The closure type for a lambda expression with no lambda capture has a public non-virtual implicit function of converting const to a pointer to work with the same parameters and return types as closing a type of a function call statement.

I understand why it is not possible to get a function pointer from lambda with state, since a function pointer cannot store any data by itself.

But when captured objects are only static members / static variable, there is no such restriction, since references to captured objects can be rigidly attached to the function itself.

struct A { static int count = 0; void foo() { static int bar = 0; auto fun = [&]()->void { count++; bar++; }; void(*ptrFun)(); ptrFun = fun; // forbidden by the quoted wording } }; 

Why is it not always possible to convert a lambda to a function pointer once the first is stateless? Am I missing something or did the committee forget this particular point?

+6
source share
1 answer

A::count does not need to be written at all. Only this and local variables should be captured. Variables with static storage duration (for example, static data members, space visibility variables, or local static function variables) do not need to be captured because they are "unique." There is only one instance of each such variable, so the reference to the object does not need to be captured.

If you remove the default capture from your lambda (i.e. change [&] to [] ) and define count , it should compile without errors. (I checked that both Visual C ++ 2012 RC and g ++ 4.5.1 accept the code, the only change I had to make was to move the built-in initialization of count , since none of these compilers support this C ++ 11 function yet .)

+9
source

Source: https://habr.com/ru/post/920754/


All Articles