Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top