就地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; }();
这比写这样的东西要好:
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
根据我在此处读到的blog,前一段代码是线程安全的。这避免了必须使用昂贵的同步。因此,您无需在后面的代码中使用互斥锁来确保同步。
我的问题是什么使前一个线程安全?如何运作?