Home » Java » C++0x – lambda expression does look same as Java's anonymous inner class?

C++0x – lambda expression does look same as Java's anonymous inner class?

Posted by: admin December 28, 2021 Leave a comment

Questions:

Is my interpretation of lambda expression in the context of c++ and Java is correct?

Answers:

They are not quite as same. Both create unnamed classes, but their similarity ends at that point.

In C++ you create a closure catching your local variables, optionally by reference. In Java, you just get a snapshot of the current local variable’s values (and those variables need to be “final”).

The purpose of anonymous inner classes is to extend another class or implement another interface ad-hoc. For that reason, anonymous inner classes can simulate the job of lambda expressions to some extend, for example by implementing the Runnable interface. Lambda expressions are specifically designed to be called and possibly modify the local variables in their environment.

###

A Java anonymous inner class can refer to final data in the enclosing method, and to all data (including mutable) in the enclosing class. So methods in anonymous classes cannot change the values of variables in the enclosing method, but they can change values of members in the enclosing class.

A C++ lambda can refer to all data (including mutable) in the enclosing function, and if it is nested inside a member function then it can do the same for the data of the enclosing class. The precise degree of dependency on the enclosing scope(s) is declared by the programmer, so it is explicit rather than implicit.

This makes them quite similar but the Java feature treats local variables/parameters in methods differently, on the principle that they should not be mutable from outside the method, especially in a language which has traditionally employed threading so casually.

Compare with C# lambdas, which have no restrictions and all dependencies are implicit. This makes them by far the least verbose of these features (also helped by them having the best type inference). But on the downside, they invalidate all the simple rules about threading, i.e. it is no longer necessarily true that local variables are “on the thread stack” and hence never require locking before access.

###

C++0x lambda expressions are unnamed methods, Javas anonymous classes are unnamed classes. So they share not having a name but the concepts are different.

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

BTW – wikipedia mentions, that only lambda functions are proposed for C++0x.