aligned_vector.h
unknown
c_cpp
a year ago
1.5 kB
7
Indexable
#ifndef ALIGNED_VECTOR_H_INCLUDED
#define ALIGNED_VECTOR_H_INCLUDED
#include <cstdlib>
#include <memory>
#include <vector>
constexpr size_t DEFAULT_MEMORY_ALIGNMENT = 64u;
template <typename T>
constexpr bool isPowerOf2(const T & n)
{
return ((n > 1) && ((n & (n - 1)) == 0));
}
template <typename T, size_t Alignment = DEFAULT_MEMORY_ALIGNMENT>
struct aligned_allocator
: public std::allocator<T>
{
static_assert(isPowerOf2(Alignment));
typedef T value_type;
aligned_allocator() = default;
template <typename T2, size_t A2>
constexpr aligned_allocator (const aligned_allocator <T2, A2>&) noexcept
{
}
[[nodiscard]] T * allocate(size_t n)
{
if (n > std::numeric_limits<size_t>::max() / sizeof(T))
throw std::bad_array_new_length();
void * p = aligned_alloc(Alignment, n * sizeof(T));
if(!p)
throw std::bad_alloc();
return static_cast<T *>(p);
}
void deallocate(T * p, [[maybe_unused]] size_t n) noexcept
{
std::free(p);
}
};
template <typename T1, size_t A1, typename T2, size_t A2>
bool operator == (const aligned_allocator<T1, A1> &,
const aligned_allocator<T2,A2> &)
{
return true;
}
template <typename T1, size_t A1, typename T2, size_t A2>
bool operator != (const aligned_allocator<T1, A1> &,
const aligned_allocator<T2,A2> &)
{
return false;
}
template <typename T, size_t Alignment = DEFAULT_MEMORY_ALIGNMENT>
using aligned_vector = std::vector<T, aligned_allocator<T, Alignment> >;
#endif // ALIGNED_VECTOR_H_INCLUDED
Editor is loading...
Leave a Comment