lambda(或函数)C++中的静态初始化

One*_*ree 2 c++ lambda static-initialization

如何确保静态字段的初始化仅在lambda的主体(或函数)中发生一次?

[] (string foo) {
   static flat_hash_set<string> set;
   // code to populate the set with some items.
   // Question: how do I ensure this population code executed exactly once?

   return set.contains(foo);
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 8

静态局部变量只初始化一次,即只有第一次控制通过它们的声明.在所有进一步的调用中,将跳过声明.因此,您可以将填充集合的代码放入函数(或另一个lambda)中,并调用它并使用返回的集合作为初始化程序.

[] (string foo) {
   static flat_hash_set<string> set = populate_the_set();
   return set.contains(foo);
}
Run Code Online (Sandbox Code Playgroud)

要么

[] (string foo) {
   static flat_hash_set<string> set = [] () {
       flat_hash_set<string> set;
       // code to populate the set with some items.
       return set;
   } ();
   return set.contains(foo);
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*ica 6

一种方法是使用一个辅助函数来返回集合,并使用它初始化lambda中的集合

static flat_hash_set<string> set = MyHelperFunction();
Run Code Online (Sandbox Code Playgroud)

你也可以使用lambda而不是helper函数来保持lambda的局部代码

flat_hash_set<string> set = []() { /* populate and return set here */ }();
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用std::call_once并将lambda传递给初始化集合的lambda.

我个人会使用第二个选项,因为它保持代码本地的lambda,你不需要全局辅助函数或std::once_flag对象