I'm going through some code from this article about ECS-systems in game programming and trying to understand it, and something I'm seeing a lot is using heap memory in places where it seems like there is no benefit in doing so. Take this as an example:
class ECS
{
public:
void someFunction()
{
archetypes.push_back(new Archetype);
}
~ECS()
{
for(Archetype* a : archetypes_)
{
delete a;
}
}
private:
std::vector<Archetype*> archetypes_;
};
This is the only way that the archetypes are manipulated in memory in the code. There is also no polymorphism involved here whatsoever. The archetypes being on the heap here has seemingly no impact on the code other than the fact that the archetypes are referenced by pointers.
Why would you ever choose to use allocated memory for this? I see this often in code and it seems to me like using heap memory just because it feels like the right thing to do, and not actually considering if it's the appropriate place for it. std::vector
already uses heap memory behind the scenes so why not just copy a stack variable into the vector when we want to add a new archetype, and let the vector handle the allocation?
class ECS
{
public:
void someFunction()
{
archetypes.push_back(Archetype());
}
private:
std::vector<Archetype> archetypes_;
};
Or are there valid reasons for using heap memory in cases like this?
Archetype
is a base type and you want to support polymorphism. But in that case you would usestd::vector<std::unique_ptr<Archetype>>
.ECS
code from theArchetype
code.Archetype*
pointers, e.g. inArchetype* ECS::GetArchetype(const ArchetypeID& id)
. If you hadstd::vector<Archetype>
, and handed out a pointer to its element, that pointer could become invalid if another archetype is later added to the vector. Maybe pointer stability is what the author was after.