Reputation: 131
I have a simple question. I have a deque,
std::deque<NPC*> enemyList
which contains dynamically allocated NPC objects. Each NPC object also has a pointer handle to a dynamically allocated Path and Shape object, which is accessible via the NPC class's getShape() and get Path() accessors.
This is how I am currently freeing the memory in this case:
while (enemyList.size() != 0) //delete npc's
{
Shape3D *sPtr = enemyList.back()->getShape();
Path *pPtr = enemyList.back()->getPath();
NPC *npcPtr = enemyList.back();
enemyList.pop_back();
delete sPtr;
delete pPtr;
delete npcPtr;
}
This code compiles and seems to work fine, but I am unsure if it is technically correct. Is this proper, and if not, what would be a better way of achieving the desired effect?
thank you!
Upvotes: 1
Views: 1315
Reputation: 1243
That should work fine--as long as no exceptions are thrown. What you really want to use is a deque of smart pointers that will delete themselves whenever they go out of scope.
Or better yet, a pointer-container, per boost.
Upvotes: 2