开发者

C++ List destructor called after every use of List's method

开发者 https://www.devze.com 2023-02-11 21:57 出处:网络
This is a follow up to a question I asked earlier today regarding the appropriation of directly calling a class\' destructor.

This is a follow up to a question I asked earlier today regarding the appropriation of directly calling a class' destructor.

I'm creating my own List for an assignment. I have overloaded the assignment, square brackets, in and out stream operators and have the basic adding, removing and printing to screen functionality.

My next step is to have the List delete and release the memory of all of its nodes, which I am having trouble with.

I have the List write to the screen its current state after performing its operations, as follows:

void main()
{
    // Create instance of list
    List aList(true);
    List bList(true);
    aList.Add(1);
    aList.Add(2);
    bList.Add(2);
    cout << "aList: " << aList;
    cout << "bList: " << bList;
    aList = bList;
    cout << "aList: " << aList;
    cout << "bList: " << bList;
    aList.Add(3);
    cout << "aList: " << aList;
    cout << "bList: " << bList;
    int i = 0; cin >> i;
}

Here is my overloaded out stream:

ostream &operator<<(ostream &stream, List theList)
{
    stream << "There are " << theList._totalNodes << " nodes in the list." << endl;
    for(int i = 0; i < theList._totalNodes; i++)
    {
        stream << "Node #" << i <&l开发者_StackOverflow社区t; " holds the data: " << theList[i] << endl;
    }
    return stream;
}

Looking at the command prompt window after this is used "Destructor called" is also printed underneath it.

The List destructor:

List::~List()
{
    cout << "Destructor called" << endl;
//  List::Destroy();
}

The overloaded assignment operator also seems to call the destructor, which doesn't surprise me. However, the others do.

List &List::operator=(List &aList)
{
    // Make sure not the same object trying to be copied
    if(this != &aList)
    {
        // Perform deep copy
        // Delete old pointers in redundant list, only if they exist already
        if(_head)
        {
            delete _head, _tail, _current, _del;
            _totalNodes = 0; // Reset total nodes
        }
        // Now set new pointers copied from other list
        _head = NULL;
        _tail = _head;
        _current = _head;
        _del = _head;
        // Now loop through all nodes in other list and copy them to this
        // Reset pointer in other list
        aList.Reset();
        for(int i = 0; i < aList._totalNodes; i++)
        {
            Add(aList.Current()->_data);
            aList.Next();
        }
        // Reset other list's pointer
        aList.Reset();
        Reset(); // Reset our pointer
    }
    return *this; // Return for multi assignment
}

I also have the destructor to a List write "Destructor called" when it's called and noticed that it is called after every use of one of its methods.

Why is this? I assumed the destructor is called when the object is no longer needed, i.e. deleted.

Furthermore, when stepping through my code I have noticed that when a pointer is deleted the memory address it is pointing to isn't being nullified. Do I have to manually NULL a pointer after it is deleted?


It's because you took your List by value- that is, you copied it. You need to take it by const reference- that is,

ostream &operator<<(ostream &stream, const List& theList)

Furthermore, your assignment operator should take a const reference, not a non-const ref.

I also don't think that this

delete _head, _tail, _current, _del;

does what you think it does. It just deletes _del and none of the others.

You should use a recursively self-owning design, where each node deletes the next one in the chain. Edit: As this was unclear, I'm going to post a brief sample.

template<typename T> struct Node {
    Node(const T& arg, Node* prev) : t(arg), previous(prev) {}
    T t;
    std::auto_ptr<Node<T>> next;
    Node<T>* previous;
};
template<typename T> class List {
    std::auto_ptr<Node<T>> head;
    Node<T>* tail;
public:
    List() : head(NULL), tail(NULL) {}
    void clear() { head = tail = NULL; } // Notice how simple this is
    void push_back() {
        push_back(T());
    }
    void push_back(const T& t) {
        if (tail) {
            tail = (tail->next = new Node<T>(t, tail)).get();
            return;
        }
        tail = (head = new Node<T>(t, NULL)).get();
    }
    void pop_back() {
        tail = tail->previous;
        tail->next = NULL;
    }
    void pop_front() {
        head = head->next;
    }
    List<T>& operator=(const List& ref) {
        clear(); // Clear the existing list
        // Copy. Gonna leave this part to you.
    }
};

Notice how I never deleted anything- std::auto_ptr did everything for me, and manipulating the list and it's nodes became much easier, because std::auto_ptr manages all of the memory involved. This list doesn't even need a custom destructor.

I suggest that you read up heavily on std::auto_ptr, it has some surprises in it's interface, like the "copy" constructor and assignment operator actually move, that you are going to want to know about before using the class. I wish I could start using std::unique_ptr instead all of the time, which would make life so much easier.


Your operator << overload is taking a List by-value. This requires a copy to be made (to create the local variable), and this local copy is destructed at the end of the overload function. This is why you're seeing the destructor being called over and over again.

Consider changing your overload to take a const List & instead. The & means that it's passed-by-reference, so no copy is made. The const means that the function guarantees not to alter the object.

0

精彩评论

暂无评论...
验证码 换一张
取 消