I think I'm experiencing some sort of memory leak using shared_ptr
. I'm trying to implement an ECS. Each system has an std::set
of entities that it should care about, and there is an system manager class that takes care of maintaining that set. It works perfectly until one of the entities is deleted. The component manager deletes all of the entities' components, but the system manager doesn't correctly delete the entity from the system's set, which causes a segmentation fault since the system then tries to access components that no longer exist. I think the problem is occurring with how I am managing storing the systems. All system inherit from a base system class:
class System {
public:
std::set m_entities;
};
The SystemManager then has an unordered_map of shared_ptrs to hold the systems. The systems get created and placed into the map through the following function:
template<typename T, typename... Args>
std::shared_ptr RegisterSystem(Args... constructorArgs) {
const char* typeName = typeid(T).name();
// Make sure the system hasn't already been registered
assert(m_systems.find(typeName) == m_systems.end() && "Registering a system more than once.");
auto system = std::make_shared(constructorArgs...);
m_systems.insert({typeName, system});
return system;
};
That way, I can use a system like so:
auto testSystem = systemManager.RegisterSystem(/*constructor arguments*/);
The system manager also has a function that the entity manager calls when it deletes an entity, which loops over all the systems that contain that entity, and erases it from the system's set of entities. It is being deleted properly from here, I can confirm that by printing the size of the set before and after the functions have been called. The entity is not being deleted from the external reference to the system, though. So in the above example, testSystem
would still contain the entity, even though it has been deleted from the std::set
on the system inside the unordered_map
... What could be going on?