当前位置: 动力学知识库 > 问答 > 编程问答 >

class - 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.

网友答案:

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');
        }
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: