简体   繁体   English

为什么要定义一个返回结构而不是直接定义结构的lambda函数?

[英]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. 使用初始值在静态时间初始化结构(如第二个示例中所示)对于微不足道的值很有用,但是,如果需要运行非平凡的初始化(并且没有构造函数),则lambda方法可以正常工作。 For example, what if you need to initialize the fields with a function that returns data with an "out" parameter? 例如,如果需要使用返回带有“out”参数的数据的函数初始化字段,该怎么办?

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. 在lambdas存在之前,你必须创建一个显式的初始化函数,并用它来初始化变量(当然,这是一个CTOR),但是现在lambdas使这个过程更加简洁。

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. 也许您正在从文件中读取内容或获取GPU资源的句柄。 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. 我从未使用过这种lambda模式。 For the example you showed, the best way to initialise default_A would be this: 对于您展示的示例,初始化default_A的最佳方法是:

static A default_a = {1, 2};

Designated initialisers are a C++20 feature. 指定的初始化程序是C ++ 20的一项功能。

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. 该代码在某些时候删除了,但lambda仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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