std_global.hpp 1.4 KB

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