Question

I'm currently learning C++ on my own and I'm having some trouble creating a destructor.

Here is what the code for the main part that I'm struggling with

#include <list>

using namespace std;

class Test
{
    private: 
        list<char> *tempList;
    public:
        Test()
        {
            tempList->push_back('a');
            tempList->push_back('b');
            tempList->push_back('c');
        }

        ~Test()
        {
            while (tempList->size() != 0)
            {
                tempList->pop_back();
            }
        }
};

As you can see I'm using the std::list to implement a doubly linked list. At the moment I'm fiddling around with it hence why the variable is named tempList and why I'm putting a,b,c in there.

What I need some assistance with is creating the destructor. I've had a go at creating my own but then I started Googling other solutions and none look like mine.

The main thing I want my destructor to do is to clean up the tempList which is a doubly linked list of char. I think what needs to happen is I need to figure out a way to delete each element in the linked list.

Was it helpful?

Solution 2

Standard class std::list has its own destrucdtor. When the destructor of class Test is called it in turn calls the destructor of std::list. There is no need to use pop_back that to remove elements from the list. It is a superflouos operation in the destructor. The memory allocated by the std::list constructor will be deleted along with characters that were placed there.

OTHER TIPS

Assuming tempList is allocated and deallocated correctly (which right now it's not), you don't have to call anything - the elements in the list will be destroyed automatically.

The simplest and cleanest solution is to not have a pointer at all:

class Test
{
    private: 
        list<char> tempList;
    public:
        Test()
        {
            tempList.push_back('a');
            tempList.push_back('b');
            tempList.push_back('c');
        }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top