std_global.hpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // detail/std_global.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_STD_GLOBAL_HPP
  11. #define BOOST_ASIO_DETAIL_STD_GLOBAL_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #if defined(BOOST_ASIO_HAS_STD_CALL_ONCE)
  17. #include <exception>
  18. #include <mutex>
  19. #include <boost/asio/detail/push_options.hpp>
  20. namespace boost {
  21. namespace asio {
  22. namespace detail {
  23. template <typename T>
  24. struct std_global_impl
  25. {
  26. // Helper function to perform initialisation.
  27. static void do_init()
  28. {
  29. instance_.ptr_ = new T;
  30. }
  31. // Destructor automatically cleans up the global.
  32. ~std_global_impl()
  33. {
  34. delete ptr_;
  35. }
  36. static std::once_flag init_once_;
  37. static std_global_impl instance_;
  38. T* ptr_;
  39. };
  40. template <typename T>
  41. std::once_flag std_global_impl<T>::init_once_;
  42. template <typename T>
  43. std_global_impl<T> std_global_impl<T>::instance_;
  44. template <typename T>
  45. T& std_global()
  46. {
  47. std::call_once(std_global_impl<T>::init_once_, &std_global_impl<T>::do_init);
  48. return *std_global_impl<T>::instance_.ptr_;
  49. }
  50. } // namespace detail
  51. } // namespace asio
  52. } // namespace boost
  53. #include <boost/asio/detail/pop_options.hpp>
  54. #endif // defined(BOOST_ASIO_HAS_STD_CALL_ONCE)
  55. #endif // BOOST_ASIO_DETAIL_STD_GLOBAL_HPP