ECSTASY
All in the name
Loading...
Searching...
No Matches
StackAllocator.hpp
Go to the documentation of this file.
1
11
12#ifndef UTIL_STACKALLOCATOR_HPP_
13#define UTIL_STACKALLOCATOR_HPP_
14
15#include <cstring>
16#include <memory>
17#include <new>
18#include <vector>
19
20namespace util
21{
30 template <size_t size, typename Base>
32 public:
36 static constexpr size_t mem_size = size;
37
45 {
46 _cursor = 0;
47 }
48
60 {
61 *this = std::move(other);
62 }
63
71 {
72 for (auto &&object : _instances)
73 (*object).~Base();
74 }
75
89 {
90 // Doesn't support overlap but we shouldn't have any
91 std::memcpy(_memory, other._memory, size);
92 _cursor = other._cursor;
93 for (Base *instance : other._instances)
94 _instances.push_back(reinterpret_cast<Base *>(reinterpret_cast<char *>(_memory)
95 + (reinterpret_cast<char *>(instance) - reinterpret_cast<char *>(other._memory))));
96
97 // Clear other
98 other._cursor = 0;
99 other._instances.clear();
100 return *this;
101 }
102
116 template <std::derived_from<Base> T, typename... Args>
117 [[nodiscard]] T &instanciate(Args &&...args)
118 {
119 T *newObject = new (reinterpret_cast<void *>(&_memory[_cursor])) T(std::forward<Args>(args)...);
120
121 _instances.push_back(newObject);
122 _cursor += sizeof(T);
123 return *newObject;
124 }
125
133 [[nodiscard]] constexpr const std::vector<Base *> &getInstances() const noexcept
134 {
135 return _instances;
136 }
137
138 private:
139 char _memory[size];
140
141 size_t _cursor;
143 };
144} // namespace util
145
146#endif /* !UTIL_STACKALLOCATOR_HPP_ */
std::vector< Base * > _instances
StackAllocator & operator=(StackAllocator &&other)
Move assignment operator.
StackAllocator()
Default constructor.
constexpr const std::vector< Base * > & getInstances() const noexcept
Access the internal instances vector.
T & instanciate(Args &&...args)
Instanciate a new instance of type T with lifetime attached to this lifetime.
static constexpr size_t mem_size
Size in byte of the allocator memory.
~StackAllocator()
Destructor.
StackAllocator(StackAllocator &&other)
Move constructor.
T memcpy(T... args)
Namespace regrouping helpers used by ecstasy but not specific to ecstasy.
Definition Queryable.hpp:21
T push_back(T... args)