初始化once_flag?

jww*_*jww 6 c++ c++11

什么是once_flag应该被初始化?我试过false0,并且都给出类似如下(以下是错误的0):

no viable conversion from 'int' to 'std::once_flag'
Run Code Online (Sandbox Code Playgroud)

这是我试图使用它的方式.(我认为即使语言初始化它们也没有初始化静态的不好的风格,所以我真的更喜欢在那里有东西).

MyClass& GetMyClass()
{
    static std::once_flag flag;
    static MyClass cls;

    std::call_once(flag, []() {
        // Initialize class
    });

    return cls;
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*our 7

更新

如果我们查看草案C++标准部分30.4.4.1 struct once_flag,我们可以看到构造函数定义为:

constexpr once_flag() noexcept;
Run Code Online (Sandbox Code Playgroud)

因为它是一个constexpr,你的静态实例将被静态初始化,我们可以在30.4.4.2 函数call_once中看到一个使用静态实例的例子:

void g() {
 static std::once_flag flag2;
 std::call_once(flag2, initializer());
}
Run Code Online (Sandbox Code Playgroud)

原版的

如果我们查看std :: once_flag的文档,它会说:

once_flag();

Cnstructs an once_flag object. The internal state is set to indicate that no function
has been called yet. 
Run Code Online (Sandbox Code Playgroud)

如果我们进一步查看call_once的文档文档,我们将看到以下示例,该示例演示了如何使用std::once_flag:

#include <iostream>
#include <thread>
#include <mutex>

std::once_flag flag; 

void do_once()
{
    std::call_once(flag, [](){ std::cout << "Called once" << std::endl; });
}

int main()
{
    std::thread t1(do_once);
    std::thread t2(do_once);
    std::thread t3(do_once);
    std::thread t4(do_once);

    t1.join();
    t2.join();
    t3.join();
    t4.join();
}
Run Code Online (Sandbox Code Playgroud)

具有以下预期输出:

Called once
Run Code Online (Sandbox Code Playgroud)