singleton.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // "$Id$"
  3. //
  4. // Copyright (c)1992-2007, ZheJiang Dahua Technology Stock CO.LTD.
  5. // All Rights Reserved.
  6. //
  7. // Description:
  8. // Revisions: Year-Month-Day SVN-Author Modification
  9. //
  10. #ifndef DAHUA_MEMORY_SINGLETON_H__
  11. #define DAHUA_MEMORY_SINGLETON_H__
  12. namespace Dahua {
  13. namespace Memory {
  14. namespace Detail {
  15. // T must be: no-throw default constructible and no-throw destructible
  16. template <typename T>
  17. struct singleton_default
  18. {
  19. private:
  20. struct object_creator
  21. {
  22. // This constructor does nothing more than ensure that instance()
  23. // is called before main() begins, thus creating the static
  24. // T object before multithreading race issues can come up.
  25. object_creator() { singleton_default<T>::instance(); }
  26. inline void do_nothing() const { }
  27. };
  28. static object_creator create_object;
  29. singleton_default();
  30. public:
  31. typedef T object_type;
  32. // If, at any point (in user code), singleton_default<T>::instance()
  33. // is called, then the following function is instantiated.
  34. static object_type & instance()
  35. {
  36. // This is the object that we return a reference to.
  37. // It is guaranteed to be created before main() begins because of
  38. // the next line.
  39. static object_type obj;
  40. // The following line does nothing else than force the instantiation
  41. // of singleton_default<T>::create_object, whose constructor is
  42. // called before main() begins.
  43. create_object.do_nothing();
  44. return obj;
  45. }
  46. };
  47. template <typename T>
  48. typename singleton_default<T>::object_creator
  49. singleton_default<T>::create_object;
  50. } // namespace Detail
  51. } // namespace Memory
  52. } // namespace Dahua
  53. #endif // DAHUA_MEMORY_SINGLETON_H__