Search code examples
c++lambdastatic-initialization

static initialization inside lambda (or function) C++


How do I ensure that the initialization of a static field happens only once inside a lambda's body (or a function's)?

[] (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);
}

Solution

  • One way to do this is to use a helper function that returns the set and initialize the set in the lambda with this

    static flat_hash_set<string> set = MyHelperFunction();
    

    You could also use a lambda instead of a helper function to keep the code local to the lambda like

    flat_hash_set<string> set = []() { /* populate and return set here */ }();
    

    Another way to do this is use std::call_once and pass a lambda to that which initializes the set.

    Personally I would use the second option as it keeps the code local to the lambda and you don't need a global helper function or std::once_flag object