1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_TYPES_FIXED_ARRAY_H_ 6 #define BASE_TYPES_FIXED_ARRAY_H_ 7 8 #include <stddef.h> 9 10 #include <memory> 11 #include <type_traits> 12 13 #include "third_party/abseil-cpp/absl/container/fixed_array.h" 14 15 namespace base { 16 17 // `FixedArray` provides `absl::FixedArray` in Chromium, but when `T` is 18 // trivially-default-constructible, forces the no-default-value constructor to 19 // initialize the elements to `T()`, instead of leaving them uninitialized. This 20 // makes `base::FixedArray` behave like `std::vector` instead of `std::array` 21 // and avoids the risk of UB. 22 23 // Trivially-default-constructible case: no-value constructor should init 24 template <typename T, 25 size_t N = absl::kFixedArrayUseDefault, 26 typename A = std::allocator<T>, 27 typename = void> 28 class FixedArray : public absl::FixedArray<T, N, A> { 29 public: 30 using absl::FixedArray<T, N, A>::FixedArray; 31 explicit FixedArray(absl::FixedArray<T, N, A>::size_type n, 32 const absl::FixedArray<T, N, A>::allocator_type& a = 33 typename absl::FixedArray<T, N, A>::allocator_type()) FixedArray(n,T (),a)34 : FixedArray(n, T(), a) {} 35 }; 36 37 // Non-trivially-default-constructible case: Pass through all constructors 38 template <typename T, size_t N, typename A> 39 struct FixedArray< 40 T, 41 N, 42 A, 43 std::enable_if_t<!std::is_trivially_default_constructible_v<T>>> 44 : public absl::FixedArray<T, N, A> { 45 using absl::FixedArray<T, N, A>::FixedArray; 46 }; 47 48 } // namespace base 49 50 #endif // BASE_TYPES_FIXED_ARRAY_H_ 51