From e11da225544b941d82b14b092cda4009820e8026 Mon Sep 17 00:00:00 2001 From: Fernando Raviola Date: Sun, 31 May 2020 11:22:41 -0300 Subject: [PATCH] Make components array in Entity a pointer --- include/ecs/ecs.h | 33 +++++++++++++++++++++++++-------- src/ecs/ecs.cpp | 4 ++-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/include/ecs/ecs.h b/include/ecs/ecs.h index 4d4b6d6..e575641 100644 --- a/include/ecs/ecs.h +++ b/include/ecs/ecs.h @@ -20,21 +20,37 @@ struct Component { class Entity { public: + Entity() : components{new std::unordered_map()} {}; + + Entity(const Entity& other) = delete; + + Entity(Entity&& other) noexcept { + this->components = other.components; + other.components = nullptr; + } + + Entity& operator=(Entity&& other) noexcept { + if (this == &other) return *this; + this->components = other.components; + other.components = nullptr; + return *this; + } + template void assign(Args&& ... arguments) { // std::forward will detect whether arguments is an lvalue or rvalue and perform a copy or move, respectively. auto* component = new ComponentType(std::forward(arguments)...); auto typeIndex = std::type_index(typeid(ComponentType)); - components.insert_or_assign(typeIndex, component); + components->insert_or_assign(typeIndex, component); } template bool remove() { auto index = std::type_index(typeid(ComponentType)); - auto found = components.find(index); - if (found != components.end()) { + auto found = components->find(index); + if (found != components->end()) { delete found->second; - components.erase(found); + components->erase(found); return true; } @@ -42,19 +58,20 @@ class Entity { } bool clearComponents() { - components.clear(); + components->clear(); return true; } template C* get() { - return static_cast(components[std::type_index(typeid(C))]); + return static_cast((*components)[std::type_index(typeid(C))]); } template [[nodiscard]] bool has() const { + if (components->empty()) return false; auto index = std::type_index(typeid(C)); - return components.find(index) != components.end(); + return components->find(index) != components->end(); } template @@ -70,7 +87,7 @@ class Entity { ~Entity(); private: - std::unordered_map components; + std::unordered_map* components; }; class System { diff --git a/src/ecs/ecs.cpp b/src/ecs/ecs.cpp index 745fcf2..03f9079 100644 --- a/src/ecs/ecs.cpp +++ b/src/ecs/ecs.cpp @@ -44,6 +44,6 @@ void World::handleEvent(SDL_Event& event) { } Entity::~Entity() { - for (auto component : components) delete component.second; - components.clear(); + for (auto& component : *components) delete component.second; + components->clear(); }