Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define a lambda function that return a struct instead of defining the struct directly?

Tags:

c++

lambda

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?

like image 889
ericcire Avatar asked Apr 25 '26 00:04

ericcire


1 Answers

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.

like image 195
cyberbisson Avatar answered Apr 27 '26 12:04

cyberbisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!