summaryrefslogtreecommitdiff
path: root/src/dynamic-array.hpp
diff options
context:
space:
mode:
authorJonathan Bradley <jcb@pikum.xyz>2023-10-06 14:42:03 -0400
committerJonathan Bradley <jcb@pikum.xyz>2023-10-06 17:20:20 -0400
commit791c153aabd579f518a9b00613459cba13734797 (patch)
tree858ec6f9a8398398a8a53ec5a886bca5825c62e0 /src/dynamic-array.hpp
parent286bf5539527500429cfca4ded0bb78406f6364b (diff)
Memory management - ctors and dtors
Diffstat (limited to 'src/dynamic-array.hpp')
-rw-r--r--src/dynamic-array.hpp28
1 files changed, 27 insertions, 1 deletions
diff --git a/src/dynamic-array.hpp b/src/dynamic-array.hpp
index 6b22f6b..284ddcc 100644
--- a/src/dynamic-array.hpp
+++ b/src/dynamic-array.hpp
@@ -7,6 +7,7 @@
#include <cstdint>
#include <cstring>
#include <cassert>
+#include <type_traits>
#define BAKE_DYN_ARRAY(T) template struct DynArray<T>;
@@ -48,6 +49,11 @@ void DynArrayDestroy(DynArrayBase *arr);
template <typename T> inline DynArray<T>::DynArray(int64_t count) {
this->elementSize = sizeof(T);
if (count > 0) DynArrayReserve(this, count);
+ if IS_CONSTRUCTIBLE(T) {
+ for (long i = 0; i < count; ++i) {
+ new (this->ptr + (i * sizeof(T))) T{};
+ }
+ }
}
template <typename T> inline DynArray<T>::DynArray() {
@@ -89,6 +95,12 @@ template <typename T> inline DynArray<T> &DynArray<T>::operator=(DynArray<T> &&r
}
template <typename T> inline DynArray<T>::~DynArray() {
+ if (this->ptr == nullptr || this->ptr == CAFE_BABE(char)) return;
+ if IS_DESTRUCTIBLE(T) {
+ for (long i = 0; i < this->elementCount; ++i) {
+ reinterpret_cast<T *>(this->ptr + (i * sizeof(T)))->~T();
+ }
+ }
DynArrayDestroy(this);
}
@@ -136,9 +148,12 @@ template <typename T> inline void DynArray<T>::Remove(std::size_t index) {
assert(index >= this->elementCount && "Invalid DynArray<T>::Remove() - Out of bounds");
uint64_t moveCount = (this->elementCount - index - 1);
auto *tmp = Pke_New(this->elementSize * moveCount);
+ if IS_DESTRUCTIBLE(T) {
+ reinterpret_cast<T>(this->ptr + (index * sizeof(T))).~T();
+ }
memcpy(tmp, this->ptr + (this->elementSize * (index + 1)), this->elementSize * moveCount);
memcpy(this->ptr + (this->elementSize * index), tmp, this->elementSize * moveCount);
- Pke_Delete(tmp, moveCount * this->elementSize);
+ Pke_Delete<T>(tmp, moveCount * this->elementSize);
this->elementCount -= 1;
}
@@ -150,8 +165,19 @@ template <typename T> inline void DynArray<T>::Reserve(int64_t count) {
}
template <typename T> inline void DynArray<T>::Resize(int64_t count) {
+ int64_t beforeCount = this->elementCount;
+ if IS_DESTRUCTIBLE(T) {
+ for (long i = count; i > beforeCount; --i) {
+ reinterpret_cast<T *>(this->ptr + (i * sizeof(T)))->~T();
+ }
+ }
if (count > 0) {
DynArrayReserve(this, count);
+ if IS_CONSTRUCTIBLE(T) {
+ for (long i = beforeCount; i < count; ++i) {
+ new (this->ptr + (i * sizeof(T))) T{};
+ }
+ }
}
this->elementCount = count;
}