如何解决如何创建可销毁的线程安全单例C ++?
class Singleton
{
static std::shared_ptr<Singleton> GetInstance()
{
static std::shared_ptr<Singleton> instance = make_shared<Singleton>();
retrun instance;
}
static void DestroyInstance()
{
// What goes in here?
}
}
我绕过sharedPtr的原因是因为我不希望其他人在他们的代码中使用Singleton时锁定,因为担心它可能会在并行线程中被破坏。我可以保证,他们不会永远坚持下去。因此,当调用DestroyInstance时,我只希望静态shared_ptr<Singleton>
减少计数,而当其他所有人让他们完成单例任务时,最终将被销毁。同样,我希望这样,一旦Singleton被销毁,就再也无法使用GetInstance
来创建它,而应该简单地返回一个nullptr
。
解决方法
您的其他函数将必须以某种方式访问对静态对象的引用。
我要做的是私下隐藏实例函数并返回引用。公用函数将照常返回共享指针的副本。
struct Singleton {
static auto GetInstance() -> std::shared_ptr<Singleton> {
return GetRef();
}
static auto DropInstance() -> void {
GetRef() = nullptr;
}
private:
static auto GetRef() -> std::shared_ptr<Singleton>& {
static auto instance = std::make_shared<Singleton>();
return instance;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。