构造首次使用+强制初始化来解决静态初始化命令惨败?

时间:2014-08-04 15:45:35

标签: c++ multithreading

众所周知,使用static initialization order fiasco (SIOF)可以解决construct on first use idiom (COFU)。但是,当从多个线程初始化变量时,此解决方案可能会引入the issue with race conditions

我试图通过以下方式避免项目中的SIOF和竞争条件。我用了COFU。我通过在cpp中使用非局部变量(c_unusedNonLocal)强制初始化目标变量。因此,感谢c_unusedNonLocal,即使没有非本地人通过B::getA访问目标变量,它也会被初始化。重要的是,它在单个线程中在main之前初始化。因此,只读访问权限应该没有竞争条件,也没有SIOF。

这是一个可行的解决方案吗?是否有任何可能的陷阱或我在单个线程或其他什么方面错误地初始化?

感谢。

A.H

struct A
{
    A() {}
};

b.h

struct B
{
    static const A& getA();
};

b.cpp

// force initialization before 'main'
// assuming that this happens in a single thread (thus no race conditions)
static const A& c_unusedNonLocal = B::getA();

const A& B::getA()
{
    static const A* result = new A();
    return *result;
}

的main.cpp

int main() {
    // _read only_ access via B::getA is now thread safe
    // because object is guaranteed (?) to be initialized before main
    return 0;
}

0 个答案:

没有答案