静态结构初始化线程安全

fja*_*sze 7 c c++ static thread-safety

给出以下示例:

struct test
{
    const char* data;
    const int number;
};

struct test* foo()
{
    static struct test t = {
        "this is some data",
        69
    };
    return &t;
}
Run Code Online (Sandbox Code Playgroud)

对线程的调用是foo安全的吗?换句话说,该结构是否仅以线程安全的方式初始化一次?如果用 C 或 C++ 编译它有什么区别吗?

小智 0

从C++11开始,对象初始化将仅由一个线程进行,其他线程将等待它完成。请参阅此线程以供参考。