singleton.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright Andrey Semashev 2007 - 2015.
  3. * Distributed under the Boost Software License, Version 1.0.
  4. * (See accompanying file LICENSE_1_0.txt or copy at
  5. * http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. /*!
  8. * \file singleton.hpp
  9. * \author Andrey Semashev
  10. * \date 20.04.2008
  11. *
  12. * \brief This header is the Boost.Log library implementation, see the library documentation
  13. * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
  14. */
  15. #ifndef BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_
  16. #define BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_
  17. #include <boost/log/detail/config.hpp>
  18. #include <boost/log/utility/once_block.hpp>
  19. #include <boost/log/detail/header.hpp>
  20. #ifdef BOOST_HAS_PRAGMA_ONCE
  21. #pragma once
  22. #endif
  23. namespace boost {
  24. BOOST_LOG_OPEN_NAMESPACE
  25. namespace aux {
  26. //! A base class for singletons, constructed on-demand
  27. template< typename DerivedT, typename StorageT = DerivedT >
  28. class lazy_singleton
  29. {
  30. public:
  31. BOOST_DEFAULTED_FUNCTION(lazy_singleton(), {})
  32. //! Returns the singleton instance
  33. static StorageT& get()
  34. {
  35. BOOST_LOG_ONCE_BLOCK()
  36. {
  37. DerivedT::init_instance();
  38. }
  39. return get_instance();
  40. }
  41. //! Initializes the singleton instance
  42. static void init_instance()
  43. {
  44. get_instance();
  45. }
  46. BOOST_DELETED_FUNCTION(lazy_singleton(lazy_singleton const&))
  47. BOOST_DELETED_FUNCTION(lazy_singleton& operator= (lazy_singleton const&))
  48. protected:
  49. //! Returns the singleton instance (not thread-safe)
  50. static StorageT& get_instance()
  51. {
  52. static StorageT instance;
  53. return instance;
  54. }
  55. };
  56. //! A base class for singletons, constructed on namespace scope initialization stage
  57. template< typename DerivedT, typename StorageT = DerivedT >
  58. class singleton :
  59. public lazy_singleton< DerivedT, StorageT >
  60. {
  61. public:
  62. static StorageT& instance;
  63. };
  64. template< typename DerivedT, typename StorageT >
  65. StorageT& singleton< DerivedT, StorageT >::instance =
  66. lazy_singleton< DerivedT, StorageT >::get();
  67. } // namespace aux
  68. BOOST_LOG_CLOSE_NAMESPACE // namespace log
  69. } // namespace boost
  70. #include <boost/log/detail/footer.hpp>
  71. #endif // BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_