std_global.hpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // detail/std_global.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 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. #include <exception>
  17. #include <mutex>
  18. #include <boost/asio/detail/push_options.hpp>
  19. namespace boost {
  20. namespace asio {
  21. namespace detail {
  22. template <typename T>
  23. struct std_global_impl
  24. {
  25. // Helper function to perform initialisation.
  26. static void do_init()
  27. {
  28. instance_.ptr_ = new T;
  29. }
  30. // Destructor automatically cleans up the global.
  31. ~std_global_impl()
  32. {
  33. delete ptr_;
  34. }
  35. static std::once_flag init_once_;
  36. static std_global_impl instance_;
  37. T* ptr_;
  38. };
  39. template <typename T>
  40. std::once_flag std_global_impl<T>::init_once_;
  41. template <typename T>
  42. std_global_impl<T> std_global_impl<T>::instance_;
  43. template <typename T>
  44. T& std_global()
  45. {
  46. std::call_once(std_global_impl<T>::init_once_, &std_global_impl<T>::do_init);
  47. return *std_global_impl<T>::instance_.ptr_;
  48. }
  49. } // namespace detail
  50. } // namespace asio
  51. } // namespace boost
  52. #include <boost/asio/detail/pop_options.hpp>
  53. #endif // BOOST_ASIO_DETAIL_STD_GLOBAL_HPP