From 791c153aabd579f518a9b00613459cba13734797 Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Fri, 6 Oct 2023 14:42:03 -0400 Subject: Memory management - ctors and dtors --- src/dynamic-array.hpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'src/dynamic-array.hpp') 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 #include #include +#include #define BAKE_DYN_ARRAY(T) template struct DynArray; @@ -48,6 +49,11 @@ void DynArrayDestroy(DynArrayBase *arr); template inline DynArray::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 inline DynArray::DynArray() { @@ -89,6 +95,12 @@ template inline DynArray &DynArray::operator=(DynArray &&r } template inline DynArray::~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(this->ptr + (i * sizeof(T)))->~T(); + } + } DynArrayDestroy(this); } @@ -136,9 +148,12 @@ template inline void DynArray::Remove(std::size_t index) { assert(index >= this->elementCount && "Invalid DynArray::Remove() - Out of bounds"); uint64_t moveCount = (this->elementCount - index - 1); auto *tmp = Pke_New(this->elementSize * moveCount); + if IS_DESTRUCTIBLE(T) { + reinterpret_cast(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(tmp, moveCount * this->elementSize); this->elementCount -= 1; } @@ -150,8 +165,19 @@ template inline void DynArray::Reserve(int64_t count) { } template inline void DynArray::Resize(int64_t count) { + int64_t beforeCount = this->elementCount; + if IS_DESTRUCTIBLE(T) { + for (long i = count; i > beforeCount; --i) { + reinterpret_cast(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; } -- cgit v1.2.3