使用就地lambda进行复杂的初始化,尤其是consts

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?

Dan*_*ica 5

我认为,“博客”是指这样的假设:const对象的使用应仅涉及读取操作,因此应安全地在多个线程中使用而无需同步。这是该“博客”部分的最后一句话:

无法更改其值,因此,可以在多线程程序中使用它,而无需进行昂贵的同步

但是,这种说法通常是不正确的。如@VTT所指出的,类可以具有mutable成员变量,或例如引用成员变量。因此,不能普遍保证const可以在没有同步的情况下安全地在多线程代码中使用对象。

您可能还会注意到,在此问题的上下文中,C ++核心准则中相应的项目ES.28根本没有提及多线程。