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 16 #ifndef BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_ 17 #define BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_ 18 19 #include <boost/log/detail/config.hpp> 20 #include <boost/log/utility/once_block.hpp> 21 #include <boost/log/detail/header.hpp> 22 23 #ifdef BOOST_HAS_PRAGMA_ONCE 24 #pragma once 25 #endif 26 27 namespace boost { 28 29 BOOST_LOG_OPEN_NAMESPACE 30 31 namespace aux { 32 33 //! A base class for singletons, constructed on-demand 34 template< typename DerivedT, typename StorageT = DerivedT > 35 class lazy_singleton 36 { 37 public: lazy_singleton()38 BOOST_DEFAULTED_FUNCTION(lazy_singleton(), {}) 39 40 //! Returns the singleton instance 41 static StorageT& get() 42 { 43 BOOST_LOG_ONCE_BLOCK() 44 { 45 DerivedT::init_instance(); 46 } 47 return get_instance(); 48 } 49 50 //! Initializes the singleton instance init_instance()51 static void init_instance() 52 { 53 get_instance(); 54 } 55 56 BOOST_DELETED_FUNCTION(lazy_singleton(lazy_singleton const&)) 57 BOOST_DELETED_FUNCTION(lazy_singleton& operator= (lazy_singleton const&)) 58 59 protected: 60 //! Returns the singleton instance (not thread-safe) get_instance()61 static StorageT& get_instance() 62 { 63 static StorageT instance; 64 return instance; 65 } 66 }; 67 68 //! A base class for singletons, constructed on namespace scope initialization stage 69 template< typename DerivedT, typename StorageT = DerivedT > 70 class singleton : 71 public lazy_singleton< DerivedT, StorageT > 72 { 73 public: 74 static StorageT& instance; 75 }; 76 77 template< typename DerivedT, typename StorageT > 78 StorageT& singleton< DerivedT, StorageT >::instance = 79 lazy_singleton< DerivedT, StorageT >::get(); 80 81 } // namespace aux 82 83 BOOST_LOG_CLOSE_NAMESPACE // namespace log 84 85 } // namespace boost 86 87 #include <boost/log/detail/footer.hpp> 88 89 #endif // BOOST_LOG_DETAIL_SINGLETON_HPP_INCLUDED_ 90