2

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);
}
1
  • 4
    static set<string>set = createSet(); Commented Feb 5, 2018 at 15:39

2 Answers 2

8

Static local variables are initialized only once, i.e. only the first time control passes through their declaration. On all further calls, the declaration is skipped. So you can put the code which populates the set into a function (or another lambda), and invoke it and use the returned set as the initializer.

[] (string foo) {
   static flat_hash_set<string> set = populate_the_set();
   return set.contains(foo);
}

or

[] (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);
}
Sign up to request clarification or add additional context in comments.

Comments

6

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

2 Comments

Then I could in theory just do flat_hash_set<string> set = []() { /* populate here */ }(); , correct?
@OneTwoThree That is another option as well. I'll add that to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.