使用std :: call_once实现类似单例的功能

时间:2018-09-21 11:36:42

标签: c++ singleton std-call-once

我想使用std :: call_once实现类似单例的功能,只是出于娱乐目的,或者可能会改善Singleton Pattern本身。到目前为止,这是我尝试过的操作,但仍然遇到问题。任何帮助将不胜感激。

class single {
public:

private:
    single(){}
    friend void boo(unique_ptr<single>&);
};

void boo(unique_ptr<single>& f) {
    f.reset(new single());
}

unique_ptr<single>& bar() {
    static once_flag flag;
    static unique_ptr<single> f;
    call_once(flag, boo,f);
    return f;
}


int main()
{
    unique_ptr<single> f;
    f = move(bar());

    unique_ptr<single> f2;
    f2 = move(bar()); // this should not work but it does, work-around?
}

1 个答案:

答案 0 :(得分:2)

static就足够了。 It does thread-safe initialization for you, no need for call_once

  

如果多个线程尝试同时初始化同一静态局部变量,则初始化仅发生一次(可以使用std::call_once获得任意函数的相似行为)。

     

注意:此功能的常规实现使用双重检查的锁定模式的变体,从而将已经初始化的局部静态数据的运行时间开销减少到单个非原子布尔比较。

因此:

unique_ptr<single>& bar() {
    static unique_ptr<single> f{new single};
    return f;
}

或更佳:

single& bar() {
    static single f;
    return f;
}
相关问题