C ++ 0x - does lambda expression look like a Java anonymous inner class?

Is my interpretation of a lambda expression in the context of C ++ and Java correct?

+6
java c ++ lambda c ++ 11
source share
3 answers

They are not exactly the same. Both create unnamed classes, but their similarity ends at this point.

In C ++, you create a closure that captures your local variables, optionally by reference. In Java, you just get a snapshot of the current values โ€‹โ€‹of a local variable (and these variables should be "final").

The goal of anonymous inner classes is to extend another class or implement a different ad-hoc interface. For this reason, anonymous inner classes can model the operation of lambda expressions to some extent, for example, by implementing the Runnable interface. Lambda expressions are specifically designed to invoke and possibly modify local variables in their environment.

+5
source share

An anonymous Java inner class can refer to final data in the inclusion method and all data (including mutable) in the enclosing class. Thus, methods in anonymous classes cannot change the values โ€‹โ€‹of variables in the environment method, but they can change the values โ€‹โ€‹of elements in the enclosing class.

C ++ lambda can refer to all data (including mutable) in a closing function, and if it is nested inside a member function, then it can do the same for the data of the enclosing class. The exact degree of dependence on the encompassing area (s) is declared by the programmer, so it is explicit, not hidden.

This makes them very similar, but the Java function treats local variables / parameters in methods differently, on the principle that they should not be changed outside the method, especially in a language that traditionally uses threads so carelessly.

Compare with C # lambdas, which have no restrictions, and all dependencies are implicit. This makes them, by far, the least verbose of these functions (also better type inference helps them). But on the other hand, they invalidate all simple streaming rules, i.e. It is no longer necessarily true that local variables are "on the thread stack" and therefore never require locking before access.

+4
source share

C ++ 0x lambda expressions are unnamed methods , anonymous Javas classes are unnamed classes . Therefore, they do not have a name, but the concepts are different.

Starting with the most obvious fact, these lambda functions (can) return a value, and anonymous classes can be used to create instances (objects).

BTW - wikipedia mentions that for C ++ 0x only lambda functions are offered.

+2
source share

All Articles