如何创建可破坏的线程安全单例 C++?
How do I create a destroyable threadsafe singleton 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
创建它,它应该只是 return a nullptr
.
您的其他函数必须以某种方式访问对静态对象的引用。
我会做的是私下隐藏实例函数和 return 引用。 public 函数会像往常一样 return 共享指针的副本。
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;
}
};
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
创建它,它应该只是 return a nullptr
.
您的其他函数必须以某种方式访问对静态对象的引用。
我会做的是私下隐藏实例函数和 return 引用。 public 函数会像往常一样 return 共享指针的副本。
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;
}
};