Reputation: 23497
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);
}
Upvotes: 2
Views: 826
Reputation: 180435
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
Upvotes: 6
Reputation: 172894
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);
}
Upvotes: 8