문제

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.

도움이 되었습니까?

해결책 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.

다른 팁

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');
        }
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top