allocator.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
  2. // Distributed under MIT license, or public domain if desired and
  3. // recognized in your jurisdiction.
  4. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  5. #ifndef JSON_ALLOCATOR_H_INCLUDED
  6. #define JSON_ALLOCATOR_H_INCLUDED
  7. #include <cstring>
  8. #include <memory>
  9. #pragma pack(push, 8)
  10. namespace Json {
  11. template <typename T> class SecureAllocator {
  12. public:
  13. // Type definitions
  14. using value_type = T;
  15. using pointer = T*;
  16. using const_pointer = const T*;
  17. using reference = T&;
  18. using const_reference = const T&;
  19. using size_type = std::size_t;
  20. using difference_type = std::ptrdiff_t;
  21. /**
  22. * Allocate memory for N items using the standard allocator.
  23. */
  24. pointer allocate(size_type n) {
  25. // allocate using "global operator new"
  26. return static_cast<pointer>(::operator new(n * sizeof(T)));
  27. }
  28. /**
  29. * Release memory which was allocated for N items at pointer P.
  30. *
  31. * The memory block is filled with zeroes before being released.
  32. * The pointer argument is tagged as "volatile" to prevent the
  33. * compiler optimizing out this critical step.
  34. */
  35. void deallocate(volatile pointer p, size_type n) {
  36. std::memset(p, 0, n * sizeof(T));
  37. // free using "global operator delete"
  38. ::operator delete(p);
  39. }
  40. /**
  41. * Construct an item in-place at pointer P.
  42. */
  43. template <typename... Args> void construct(pointer p, Args&&... args) {
  44. // construct using "placement new" and "perfect forwarding"
  45. ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
  46. }
  47. size_type max_size() const { return size_t(-1) / sizeof(T); }
  48. pointer address(reference x) const { return std::addressof(x); }
  49. const_pointer address(const_reference x) const { return std::addressof(x); }
  50. /**
  51. * Destroy an item in-place at pointer P.
  52. */
  53. void destroy(pointer p) {
  54. // destroy using "explicit destructor"
  55. p->~T();
  56. }
  57. // Boilerplate
  58. SecureAllocator() {}
  59. template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
  60. template <typename U> struct rebind { using other = SecureAllocator<U>; };
  61. };
  62. template <typename T, typename U>
  63. bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  64. return true;
  65. }
  66. template <typename T, typename U>
  67. bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  68. return false;
  69. }
  70. } // namespace Json
  71. #pragma pack(pop)
  72. #endif // JSON_ALLOCATOR_H_INCLUDED