0

I am creating a singleton class in the multithreaded environment and any thread can delete the singleton object. I want to protect this. I read somewhere to avoid this problem we can make the destructor private and can provide a destroy method.. how can we do this? Sample code will help..

Thanks in advance.

2
  • Don't use a singleton. Make an abstract class and pass around an instance of a subclass. Commented Apr 17, 2012 at 7:00
  • Simple solution don't give them a pointer. Give the user a reference then they are not allowed to delete it. See: stackoverflow.com/a/1008289/14065 Commented Apr 17, 2012 at 8:35

3 Answers 3

4
class Singleton; // forward declaration Singleton * s = NULL; // global object available to all threads // Place this class in a location unavailable to all threads except Main thread class ManageSingleton { public: static void DestroySingleton(Singleton * s) { delete s; } } class Singleton { friend class ManageSingleton; protected: ~Singleton() {} }; void main() { s = new Singleton; while (...) { // other threads access Singleton object until program is finished } // Program is now finished; destroy Singleton object ManageSingleton::DestroySingleton(s); } 
Sign up to request clarification or add additional context in comments.

Comments

3

threading really works against this design, especially if you want a pure singleton. you can visualize it like so:

class t_singleton { public: static t_singleton& Get() { /* thread safety is a consideration here: */ t_auto_ptr<t_singleton>& shared(Shared()); if (shared.isNull()) { shared.setObject(new t_singleton); } /* and you should manage external references using another container type: */ return Shared().reference(); } static void DestroyIt() { /* thread safety is a consideration here: */ Shared().destroy(); } private: static t_auto_ptr<t_singleton>& Shared() { static t_auto_ptr<t_singleton> s_Shared; return s_Shared; } private: t_singleton(); ~t_singleton(); }; 

but this should also suggest many threading red flags with pure singletons.

If you really want to extend this and enforce a pure singleton, you would need proper reference counting containers -- this suggests a singleton is a bad solution for this problem in multiple ways, and just adds a ton of unnecessary complexity. good luck!

Comments

1

Make the destructor private and provide a Destroyer class that is responsible for destroying and cleaning up all the memory of the Singleton. It will need to be a friend of the Singleton class. To add to that, are you sure you absolutely need a singleton? Or is this another overuse scenario?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.