Ian van Wijk
Ian van Wijk

Reputation: 159

Right way to delete container

When destructing a class with a container in the class for example:

class randomClass
{
    ...
    private:
        queue<myClass*> *myQueue;
    ...
};

What is the correct why to delete the queue:

First option:

randomClass::~randomClass()
{
    delete myQueue;
}

Second option:

randomClass::~randomClass()
{
    while(myQueue.size() > 0)
    {
        myClass *tmp;
        tmp = myQueue->front();

        delete tmp;
        myQueue->pop();
    }

    delete myQueue;
}

Upvotes: 1

Views: 113

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Since you are using regular pointers (as opposed to smart pointers) the second option is the one to use, because it prevents memory leaks.

A more C++ way of coding this would be using smart pointers (i.e. std::unique_ptr or std::shared_ptr) instead of plain pointers. Then the first option would work correctly.

Finally, you may want to make the myQueue an object, instead of a pointer. This would free you from the need to write your destructor, along with a copy constructor and an assignment operator.

Upvotes: 2

Related Questions