A Singleton Not Named Bridget

Ok. I haven’t posted anything in a (relative) long time. To tell the truth — there isn’t much to report.

Just for the sake of posting something: Here’s my singleton hack from the big bag of stupid-c++-tricks that I wrote for some plugins in melies fx. The following is generally a bad idea for implementing any normal singleton, except in my case where I had to implement one without the client class being aware of its singleton nature. The solution will only work on a class that do not initialize nor assign member variables in the constructor.

  1. static void* g_pkInstance;
  2.  
  3. class MySingleton
  4. {
  5. public:
  6. static void *operator new(std::size_t size)
  7. {
  8. if (!g_pkInstance)
  9. g_pkInstance = ::operator new(size);
  10.  
  11. return g_pkInstance;
  12. }
  13.  
  14. MySingleton()
  15. {
  16. }
  17.  
  18. ~MySingleton()
  19. {
  20. }
  21. };
This entry was posted in Tutorials and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.