jig*_*ius 3 c++ multithreading c++11 c++14
就地lambda可以用于复杂的初始化。因此,您可以执行以下操作:
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; }();
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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?