C++ 如何创建可破坏的线程安全单例C++;? 类单例 { 静态std::shared_ptr GetInstance() { 静态std::shared_ptr instance=make_shared(); retrun实例; } 静态实例() { //这里放什么? } }

C++ 如何创建可破坏的线程安全单例C++;? 类单例 { 静态std::shared_ptr GetInstance() { 静态std::shared_ptr instance=make_shared(); retrun实例; } 静态实例() { //这里放什么? } },c++,multithreading,static,singleton,C++,Multithreading,Static,Singleton,我之所以传递sharedPtr,是因为我不希望其他人在代码中使用单例时使用锁,担心它会在并行线程中被破坏。我可以保证他们不会永远坚持下去。因此,当调用DestroyInstance时,我只希望静态的共享的\u ptr将计数减少1,当其他所有人都处理完他们的单例时,它最终会被销毁。此外,我还希望这样,一旦单例被销毁,就不能再使用GetInstance创建它,它应该只返回nullptr,您的其他函数必须以某种方式访问静态对象的引用 我要做的是隐藏实例函数并返回一个引用。公共函数将像往常一样返回共享指

我之所以传递sharedPtr,是因为我不希望其他人在代码中使用单例时使用锁,担心它会在并行线程中被破坏。我可以保证他们不会永远坚持下去。因此,当调用DestroyInstance时,我只希望静态的
共享的\u ptr
将计数减少1,当其他所有人都处理完他们的单例时,它最终会被销毁。此外,我还希望这样,一旦单例被销毁,就不能再使用
GetInstance
创建它,它应该只返回
nullptr

,您的其他函数必须以某种方式访问静态对象的引用

我要做的是隐藏实例函数并返回一个引用。公共函数将像往常一样返回共享指针的副本

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?
   }
}
struct Singleton{
静态自动获取实例()->std::shared\u ptr{
返回GetRef();
}
静态自动DropInstance()->void{
GetRef()=nullptr;
}
私人:
静态自动GetRef()->std::shared_ptr&{
静态自动实例=std::make_shared();
返回实例;
}
};

我在你的问题中看不到一个问号。最好只选一个。它作为注释出现在代码中:D这样行吗?不行,如果你有问题,问号应该在你的文章的实际陈述中。
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;
    }
};