简体   繁体   中英

C++ Destructors using pop_back

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.

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');
        }
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM