I have the following structure...
A stripped-down definition of CContainer includes:Code:class CItem {}; class CWeapon: public CItem{}; class CArmor: public CItem{}; class CContainer: public CItem{}; //bags, chests, sacks, ...
Let's assume I allocate memory for a CWeapon instance and as the game progress the player moves the weapon inside a container. When the destructor for that CWeapon instance is called, I'll be left with a dangling pointer in contents_ which I will want to manage.Code:class CContainer : public CItem { public: CContainer() {}; virtual ~CContainer() {}; CContainer& add(CItem*); // manage contents_ CContainer& remove(CItem*); // manage contents_ // Fills the instance from equip.dat. Builds up on CItem::load() virtual CContainer& load(const std::string&); private: std::vector<CItem*> contents_; };
More, the CContainer functions responsible for reporting the CContainer instance contents will either break or become undefined.
What is the best way to manage the pointer?
I'm thinking providing CItem, CWeapon, CArmor and CContainer (I allow containers inside containers) dtors with some form of checking to have them removed from the contents_ vector. A way to speed this would be to add a new CContainer* data member to all of them that would be either null or point to the container in which the object is.
The dtors would then be able to check this and call CContainer& remove(CItem*); before deleting it.
My question is: Is there a better way?



LinkBack URL
About LinkBacks



CornedBee
Want to add some