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