recycling_allocator.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. //
  2. // detail/recycling_allocator.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_RECYCLING_ALLOCATOR_HPP
  11. #define ASIO_DETAIL_RECYCLING_ALLOCATOR_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 "asio/detail/memory.hpp"
  17. #include "asio/detail/thread_context.hpp"
  18. #include "asio/detail/thread_info_base.hpp"
  19. #include "asio/detail/push_options.hpp"
  20. namespace asio {
  21. namespace detail {
  22. template <typename T, typename Purpose = thread_info_base::default_tag>
  23. class recycling_allocator
  24. {
  25. public:
  26. typedef T value_type;
  27. template <typename U>
  28. struct rebind
  29. {
  30. typedef recycling_allocator<U, Purpose> other;
  31. };
  32. recycling_allocator()
  33. {
  34. }
  35. template <typename U>
  36. recycling_allocator(const recycling_allocator<U, Purpose>&)
  37. {
  38. }
  39. T* allocate(std::size_t n)
  40. {
  41. void* p = thread_info_base::allocate(Purpose(),
  42. thread_context::top_of_thread_call_stack(),
  43. sizeof(T) * n, alignof(T));
  44. return static_cast<T*>(p);
  45. }
  46. void deallocate(T* p, std::size_t n)
  47. {
  48. thread_info_base::deallocate(Purpose(),
  49. thread_context::top_of_thread_call_stack(), p, sizeof(T) * n);
  50. }
  51. };
  52. template <typename Purpose>
  53. class recycling_allocator<void, Purpose>
  54. {
  55. public:
  56. typedef void value_type;
  57. template <typename U>
  58. struct rebind
  59. {
  60. typedef recycling_allocator<U, Purpose> other;
  61. };
  62. recycling_allocator()
  63. {
  64. }
  65. template <typename U>
  66. recycling_allocator(const recycling_allocator<U, Purpose>&)
  67. {
  68. }
  69. };
  70. template <typename Allocator, typename Purpose>
  71. struct get_recycling_allocator
  72. {
  73. typedef Allocator type;
  74. static type get(const Allocator& a) { return a; }
  75. };
  76. template <typename T, typename Purpose>
  77. struct get_recycling_allocator<std::allocator<T>, Purpose>
  78. {
  79. typedef recycling_allocator<T, Purpose> type;
  80. static type get(const std::allocator<T>&) { return type(); }
  81. };
  82. } // namespace detail
  83. } // namespace asio
  84. #include "asio/detail/pop_options.hpp"
  85. #endif // ASIO_DETAIL_RECYCLING_ALLOCATOR_HPP