28template<
typename T,
size_t ALIGNMENT = 0>
class MemBuffer
44 : dat(static_cast<T*>(my_malloc(size * sizeof(T))))
64 std::swap(dat, other.dat);
66 std::swap(sz , other.sz);
81 [[nodiscard]]
const T*
data()
const {
return dat; }
82 [[nodiscard]] T*
data() {
return dat; }
103 [[nodiscard]]
bool empty()
const {
return !dat; }
114 dat =
static_cast<T*
>(my_realloc(dat, size *
sizeof(T)));
143 static constexpr bool SIMPLE_MALLOC = ALIGNMENT <=
alignof(std::max_align_t);
145 [[nodiscard]]
static void* my_malloc(
size_t bytes)
148 if constexpr (SIMPLE_MALLOC) {
149 result = malloc(bytes);
150 if (!result && bytes)
throw std::bad_alloc();
158 static void my_free(
void* p)
160 if constexpr (SIMPLE_MALLOC) {
167 [[nodiscard]]
void* my_realloc(
void* old,
size_t bytes)
170 if constexpr (SIMPLE_MALLOC) {
171 result = realloc(old, bytes);
172 if (!result && bytes)
throw std::bad_alloc();
175 if (!result && bytes)
throw std::bad_alloc();
This class manages the lifetime of a block of memory.
~MemBuffer()
Free the memory buffer.
MemBuffer()
Construct an empty MemBuffer, no memory is allocated.
void resize(size_t size)
Grow or shrink the memory block.
MemBuffer(size_t size)
Construct a (uninitialized) memory buffer of given size.
bool empty() const
No memory allocated?
MemBuffer(MemBuffer &&other) noexcept
Move constructor.
MemBuffer & operator=(MemBuffer &&other) noexcept
Move assignment.
const T * data() const
Returns pointer to the start of the memory buffer.
const T & operator[](size_t i) const
Access elements in the memory buffer.
void clear()
Free the allocated memory block and set the current size to 0.
void * mallocAligned(size_t alignment, size_t size)
This file implemented 3 utility functions: