I have a scenario in which I need to collect all the objects of a type in a collection, but I also need a collection of some of its inherited types. Example:
class Particle: public someClass
{
...
public:
static std::vector<std::shared_ptr<Particle>> particleCollection;
}
class ChargedParticle: public Particle
{
...
public:
static std::vector<std::shared_ptr<ChargedParticle>> chargedParticleCollection;
}
However when I want to destroy these objects, I actually call the destructor twice for every ChargedPartice:
Particle::particleCollection.clear(); // Okay
ChargedParticle::chargedParticleCollection.clear(); // Error: particles are already deleted
How can I both have a collection of the child objects stored in its static container and have smart pointers pointing on them by one of their parent classes?
I want to be able to create objects from the parent class too, and have the parent's static smart pointer vector be the owner of these objects.
My idea is that I somehow define a custom deleter for the parent class smart pointers that only calls the destructor, when the object is not an element of the child class' collection. Is this possible?