3 ms·
In JavaScript it's quite common to see self executing lambdas like this (not empty though), because there variables have function scope rather than block scope
by Too 11y ago
In JavaScript it's quite common to see self executing lambdas like this (not empty though), because there variables have function scope rather than block scope so it's a way to limit the scope and capture closures. Does it have any practical use in c++?
- tunah2 11y agoLazy initialization is one example: void foo() { // initialized once when foo is first called static auto lazy_data = ...; // use lazy_data... } As of c++11, the compiler is required to make this threadsafe (initializer only runs once, even if foo() is called concurrently), typically by inserting locks. Since this only applies to the initializer, for complex initialization a self-executing lambda can be used: void foo() { static auto lazy_data = []{ auto data = new Whatever(); // initialize data... return data; }(); // use lazy_data... }
- catnaroek 11y agoNo, you don't need this in C++. You can use a normal (brace-delimited) block for this purpose.
- evincarofautumn 11y agoThe key difference being that a lambda is an expression, while a block is not, unless you use GCC’s statement-expression syntax of “({…})”.
- catnaroek 11y agoOh, I forgot that, you're absolutely right. I'm getting too used to languages where everything is an expression. :-)
- mfukar 11y agoOf course; with generic lambdas it's absolutely possible to code in a functional style: https://gist.github.com/mfukar/3214a140a5a3b35c59fa https://gist.github.com/mfukar/3214a140a5a3b35c59fa That includes all the JS pass-a-lambda-as-a-callback shenanigans.