default-init-alloc.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (C) 2017-2022 Free Software Foundation, Inc.
  2. This file is part of GDB.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #ifndef COMMON_DEFAULT_INIT_ALLOC_H
  14. #define COMMON_DEFAULT_INIT_ALLOC_H
  15. namespace gdb {
  16. /* An allocator that default constructs using default-initialization
  17. rather than value-initialization. The idea is to use this when you
  18. don't want to default construct elements of containers of trivial
  19. types using zero-initialization. */
  20. /* Mostly as implementation convenience, this is implemented as an
  21. adapter that given an allocator A, overrides 'A::construct()'. 'A'
  22. defaults to std::allocator<T>. */
  23. template<typename T, typename A = std::allocator<T>>
  24. class default_init_allocator : public A
  25. {
  26. public:
  27. /* Pull in A's ctors. */
  28. using A::A;
  29. /* Override rebind. */
  30. template<typename U>
  31. struct rebind
  32. {
  33. /* A couple helpers just to make it a bit more readable. */
  34. typedef std::allocator_traits<A> traits_;
  35. typedef typename traits_::template rebind_alloc<U> alloc_;
  36. /* This is what we're after. */
  37. typedef default_init_allocator<U, alloc_> other;
  38. };
  39. /* Make the base allocator's construct method(s) visible. */
  40. using A::construct;
  41. /* .. and provide an override/overload for the case of default
  42. construction (i.e., no arguments). This is where we construct
  43. with default-init. */
  44. template <typename U>
  45. void construct (U *ptr)
  46. noexcept (std::is_nothrow_default_constructible<U>::value)
  47. {
  48. ::new ((void *) ptr) U; /* default-init */
  49. }
  50. };
  51. } /* namespace gdb */
  52. #endif /* COMMON_DEFAULT_INIT_ALLOC_H */