I have seen some code that basically does this:
struct A {
int a;
int b;
};
static A default_a = []() {
A ret;
ret.a = 1;
ret.b = 2;
return ret;
}();
Why is it written this way? I would have just written:
static A default_a {
.a = 1,
.b = 2,
};
Is either of these preferred?
Initializing a structure at static time with initial values (like in your second example) is great for trivial values, however, if you need to run non-trivial initializations (and don't have a constructor), the lambda approach works. For example, what if you need to initialize the fields with a function that returns data with an "out" parameter?
Prior to the existence of lambdas, you would have to create an explicit initialization function, and use it to initialize the variables (this is, of course, what a CTOR is), but now lambdas make this process a little more concise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With