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

Realize a singleton-like functionality using std::call_once

本文关键字:单例 功能 once std call 使用 实现      更新时间:2023-10-16

我想使用 std::call_once 实现类似单例的功能,只是为了好玩,或者也许可以改进单例模式本身。这是我到目前为止尝试过的,但我被卡住了。任何帮助将不胜感激。

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?
}

static就足够了。它为您执行线程安全初始化,无需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;
}