简体   繁体   中英

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

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.

You would do this when initialising the struct is more complicated than just setting members to compile-time constants. Maybe you're reading stuff from a file or obtaining a handle to a GPU resource. I personally prefer to write a function that initialises the object because a function has a descriptive name and can be reused. I've never used this lambda pattern. For the example you showed, the best way to initialise default_A would be this:

static A default_a = {1, 2};

Designated initialisers are a C++20 feature.

Looks like a refactoring artifact to me. The code used to do something different in the past that required more complex initialization code. That code was removed at some point but the lambda stayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM