SingletonHolder.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // SingletonHolder.h
  3. //
  4. // Library: Foundation
  5. // Package: Core
  6. // Module: SingletonHolder
  7. //
  8. // Definition of the SingletonHolder template.
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #ifndef Foundation_SingletonHolder_INCLUDED
  16. #define Foundation_SingletonHolder_INCLUDED
  17. #include "Poco/Foundation.h"
  18. #include "Poco/Mutex.h"
  19. namespace Poco {
  20. template <class S>
  21. class SingletonHolder
  22. /// This is a helper template class for managing
  23. /// singleton objects allocated on the heap.
  24. /// The class ensures proper deletion (including
  25. /// calling of the destructor) of singleton objects
  26. /// when the application that created them terminates.
  27. {
  28. public:
  29. SingletonHolder():
  30. _pS(0)
  31. /// Creates the SingletonHolder.
  32. {
  33. }
  34. ~SingletonHolder()
  35. /// Destroys the SingletonHolder and the singleton
  36. /// object that it holds.
  37. {
  38. delete _pS;
  39. }
  40. S* get()
  41. /// Returns a pointer to the singleton object
  42. /// hold by the SingletonHolder. The first call
  43. /// to get will create the singleton.
  44. {
  45. FastMutex::ScopedLock lock(_m);
  46. if (!_pS) _pS = new S;
  47. return _pS;
  48. }
  49. void reset()
  50. /// Deletes the singleton object.
  51. {
  52. FastMutex::ScopedLock lock(_m);
  53. delete _pS;
  54. _pS = 0;
  55. }
  56. private:
  57. S* _pS;
  58. FastMutex _m;
  59. };
  60. } // namespace Poco
  61. #endif // Foundation_SingletonHolder_INCLUDED