TransWikia.com

How do I create a destroyable threadsafe singleton C++?

Stack Overflow Asked by rstr1112 on January 23, 2021

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

The reason I pass around a sharedPtr is because I don’t want others to take a lock while using the Singleton in their code with the fear that it might get destroyed in a parallel thread. I can gurantee that they won’t hold on to it for ever. So when DestroyInstance is called I just want the static shared_ptr<Singleton> to reduce count by one and when everyone else lets are done with their singleton it’ll eventualy get destroyed. Also I’d want it such that once the Singleton is destroyed it can never be created again with GetInstance and it should simply return a nullptr.

One Answer

Your other function would have to get access to a reference to the static object somehow.

What I would do is to hide the instance function privately and return a reference. The public function would return the copy of the shared pointer as usual.

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

Correct answer by Guillaume Racicot on January 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP