【发布时间】:2018-09-21 11:36:41
【问题描述】:
我想使用 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?
}
【问题讨论】:
-
@FrederikDeRuyck:链接排除了没有 call_once 的答案
-
当我阅读你的代码时,你第一次调用bar时会返回单音,但是下次调用bar时,bar会返回一个空的unique_ptr,这不常见。
-
@Oliv:是的,你是对的,我尝试在那里使用静态。哇,它至少可以编译。我想将 boo() 隐藏在命名空间中。但是在 main() 中的 move(bar() 之后,bar 中的实例可能有问题
-
所以现在考虑标准确保静态本地函数(如
f)只初始化一次。所以这里有某种形式的代码重复。
标签: c++ singleton std-call-once