2 ms·
C++ closures do not, by themselves, use the heap. Every closure in C++ gets translated by the compiler to a unique type that contains either copies of or refere
by kccqzy 8y ago
C++ closures do not, by themselves, use the heap. Every closure in C++ gets translated by the compiler to a unique type that contains either copies of or references to the objects being closed over. If you choose to use copies, then whether or not anything is allocated on the heap depends on the copy constructor; if you use references then there is no copying, but it's up to you to ensure lifetime.
- jdmichal 8y agoThis is roughly how Java works with anonymous types closing over variables also. That's why the variables must be declared `final`. It just copies the local values over into the anonymous type and calls it a day. Of course, since the only thing allocated on the stack are primitives and pointers, and everything on the heap is subject to garbage collection, this is a pretty straight-forward operation. I don't know if lambdas work the same way. I know in some ways they work like anonymous types, and not in others.
- _old_dude_ 8y agoyes, it works the same way with lambdas, the lambda proxy (the class that implements the functional interface) contains the copy of the local values. Here is the code that generate the constructor of a lambda proxy http://hg.openjdk.java.net/jdk/jdk/file/3cabb47758c9/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java#l356 http://hg.openjdk.java.net/jdk/jdk/file/3cabb47758c9/src/jav...