dune-common 2.12-git
Loading...
Searching...
No Matches
alignedallocator.hh
Go to the documentation of this file.
1// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2// vi: set et ts=4 sw=2 sts=2:
3// SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
4// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
5#ifndef DUNE_ALIGNED_ALLOCATOR_HH
6#define DUNE_ALIGNED_ALLOCATOR_HH
7
8#include <algorithm>
9#include <bit>
10#include <cstddef>
11#include <limits>
12#include <new>
13#include <type_traits>
14
15namespace Dune
16{
17
32 template<class T, std::size_t MinAlignment = 1>
34 {
35
36 public:
37
39 template<class U>
44
46 using value_type = T;
47
48 static_assert(std::has_single_bit(MinAlignment), "MinAlignment must be a power of 2");
49
51 static constexpr std::size_t alignment = std::max(MinAlignment, std::alignment_of_v<T>);
52
54 AlignedAllocator() noexcept = default;
55
57 template<class U>
58 AlignedAllocator(const AlignedAllocator<U, MinAlignment>&) noexcept
59 {
60 }
61
68 {
69 if (n > std::numeric_limits<std::size_t>::max() / sizeof(T))
71 return static_cast<T*>(
72 ::operator new(n * sizeof(T), std::align_val_t{ alignment }));
73 }
74
80 void deallocate(T* p, std::size_t n)
81 {
82 // Clang some times does not enable sized deallocations when compiled with stdlibc++
83#if __cpp_sized_deallocation >= 201309
84 ::operator delete(p, n * sizeof(T), std::align_val_t{ alignment });
85#else
86 ::operator delete(p, std::align_val_t{ alignment });
87#endif
88 }
89 };
90
92 template <class T, class U, std::size_t A>
93 bool operator==(const AlignedAllocator<T, A>&, const AlignedAllocator<U, A>&) noexcept { return true; }
94
95} // namespace Dune
96
97#endif // DUNE_ALIGNED_ALLOCATOR_HH
Dune namespace
Definition alignedallocator.hh:16
bool operator==(const AlignedAllocator< T, A > &, const AlignedAllocator< U, A > &) noexcept
Compare two aligned allocators of different types for equality.
Definition alignedallocator.hh:93
Allocators which guarantee a minimum alignment of the memory.
Definition alignedallocator.hh:34
void deallocate(T *p, std::size_t n)
Deallocate memory previously allocated with allocate()
Definition alignedallocator.hh:80
AlignedAllocator() noexcept=default
Default constructor.
T value_type
Type of the object to allocate.
Definition alignedallocator.hh:46
T * allocate(std::size_t n)
Allocate n objects of type T.
Definition alignedallocator.hh:67
static constexpr std::size_t alignment
Alignment of the allocated memory.
Definition alignedallocator.hh:51
Rebind allocator to type U.
Definition alignedallocator.hh:41
T alignment_of_v
T has_single_bit(T... args)
T max(T... args)