In-place lambdas can be used for complex initialisation. So you can do something like this:
const widget x = [&]{
widget val; // assume that widget has a default constructor
for (auto i = 2; i <= N; ++i) { // this could be some
val += some_obj.do_something_with(i); // arbitrarily long code
} // needed to initialize x
return val; }();
This is better than writing something like this:
widget x; // should be const, but:
for (auto i = 2; i <= N; ++i) { // this could be some
x += some_obj.do_something_with(i); // arbitrarily long code
} // needed to initialize x
// from here, x should be const, but we can't say so in code in this style
According to the blog where I read this, the former bit of code is thread safe. This avoids having to use expensive synchronisation. So you wouldn't need to use mutex locking for the latter bit of code to ensure synchronisation.
My question is what makes the former thread safe? How does it work?
Aucun commentaire:
Enregistrer un commentaire