开发者

Linked list problem with constructor and destructor

开发者 https://www.devze.com 2023-01-24 02:04 出处:网络
Hi I have some issue regarding constructor and destructor. I have list class, which has two inner classes, one private class for the list nodes, and one public iterator class.

Hi I have some issue regarding constructor and destructor. I have list class, which has two inner classes, one private class for the list nodes, and one public iterator class.

Now for the issue, I have written a non-member print function which uses the inner iterator class. When i use this non-member function it will end calling the destructor for the iterator. It doesn't end here though because for some reason it will also call for the list class's destructor. Which causes some problem when I want to print the list content again.

开发者_运维问答

I don't understand why it call the list class destructor as well and wonder if someone kindly can tell me that, and how I should fix it.

I have attached all the code related to the problem

Main

#include <iostream>

#include "sorted_list.h"
#include "iterator.h"
using namespace std;

void list_print(ostream& os, sorted_list list)
{
    sorted_list::iteratorn it(&list);

    while( ! it.iterator_end())
    {
        os <<   "key = " << setw(3) << it.iterator_get_key()   << ", "
        << "value = " << setw(5) << it.iterator_get_value() << endl;
        it.iterator_next();
    }

    os << endl;
}

int main()
{


    sorted_list a;
    a.insert(4,4);
    a.insert(5,5);


    list_print(cout,a);
    list_print(cout,a);
}

sorted_list.cc

#include "sorted_list.h"

sorted_list::sorted_list()
{
    cout << "construct sorted_list" << endl;
    this->first = 0;
}
sorted_list::~sorted_list()
{
    cout << "destruct sorted_list" << endl;
    destroy(this->first);

}

void sorted_list::destroy(list_link* item)
{
    cout << "destroy list_link" << endl;
    if(item)
    {
        destroy(item->next);
        delete item;
    }

}

void sorted_list::insert(int key, double value)
{
    list_link *curr;
    list_link *prev = 0;

    curr = first;

    while(curr)
    {
        if(value < curr->value)
            break;

        prev = curr;
        curr = curr->next;
    }
    if(this->first == 0 || prev == 0) //if empty or add first
    {
        //first = create(key, value, this->first);
        first = new list_link(key, value, this->first);
    }
    else if(curr == 0)
    {
        //prev->next = create(key, value, 0);
        prev->next = new list_link(key, value, 0);
    }
    else
    {
        //prev->next = create(key, value, curr);
        prev->next = new list_link(key, value, curr);
    }
}

void sorted_list::remove(my_key_type key)
{
    list_link *curr = first;;
    list_link *prev = 0;

   while(curr)
   {
      if(curr->key == key)
      {
         list_link *remove;

         if(prev == 0)
         {
            first = curr->next;
            delete curr;
            curr = first;
         }
         else
         {
            remove = curr;
            curr = curr->next;
            prev->next = curr;
            delete remove;
         }
         continue;
      }
      prev = curr;
      curr = curr->next;
   }
}


sorted_list::list_link* sorted_list::clone(list_link* item)
{
   list_link* copyItem= new list_link(item->key,item->value,0);
   if(item->next!= 0)

      copyItem->next=clone(item->next);
   return copyItem;
    // ADD YOUR CODE HERE ( 4 well formatted lines in reference solution )

}

void sorted_list::copy(sorted_list* my_this_destination)
{
  if (my_this_destination->first == 0) // copy if empty
  {
      cout << "Copy" << endl;
    //list_destroy(my_this_destination);
    my_this_destination->first = clone(first);
  }
}

double sorted_list::find(int key)
{
    list_link *travel = this->first;
    while(travel)
    {
        cout << travel->key << "==" << key << endl;
        if(travel->key == key)
            return travel->key;

        travel = travel->next;
    }
    return -1;
}

int sorted_list::size()
{
    list_link *travel = this->first;
    int i = 0;
    while( travel )
    {
        travel = travel->next;
        i++;
    }
    return i;
}

sorted_list.h

#ifndef _SORTED_LIST_H_
#define _SORTED_LIST_H_

#include <iostream>

#include <iomanip>
using namespace std;

typedef int     my_key_type;
typedef double  my_value_type;

class sorted_list
{

public:
    sorted_list(); 
    ~sorted_list();

    void insert(int key, double value);
    void remove(my_key_type key);
    void copy(sorted_list* my_this_destination);
    void destroy();
    void init(struct my_list* my_this);
    void print();
    void print2();
    double find(int key);
    int  size();

private:
    class list_link // An inner class inside sorted_list
    {
    public:
        list_link (my_key_type key, my_value_type value, list_link* next = 0);
        ~list_link();
        my_key_type key;
        my_value_type value;
        list_link *next;
    };

    list_link* first;
    list_link* clone(list_link* item);
    void destroy(list_link* item);
    // More declarations

public:
    class iteratorn
    {
    public:
        iteratorn();
        ~iteratorn();
        iteratorn(sorted_list *item);
        list_link* list_begin();
        bool iterator_end();
        void iterator_next();
        int iterator_get_key();
        double iterator_get_value();

    private:
        sorted_list::list_link* current;
    };
};


#endif

iteratorn.cc

#include "iterator.h"
#include "sorted_list.h"

 sorted_list::iteratorn::iteratorn()
 {
 }
sorted_list::iteratorn::iteratorn(sorted_list *list)
{
    cout << "construct iteratorn" << endl;
    this->current = list->first;
}

sorted_list::iteratorn::~iteratorn()
{
    cout << "destruct iteratorn" << endl;
}

sorted_list::list_link* sorted_list::iteratorn::list_begin()
{
    return current;
}

void sorted_list::iteratorn::iterator_next()
{
  current = current->next;
}

int sorted_list::iteratorn::iterator_get_key()
{
  return current->key;
}

double sorted_list::iteratorn::iterator_get_value()
{
  return current->value;
}

list_link.cc

#include "sorted_list.h"


sorted_list::list_link::list_link(my_key_type key, my_value_type value, list_link* next)
{
    this->key = key;
    this->value = value;
    this->next = next;
}

sorted_list::list_link::~list_link()
{
    cout << "list_link destructor" << endl;
}


Your function void list_print(ostream& os, sorted_list list) takes a sorted_list parameter by copy. A quick and dirty fix (that you should do anyways for performance reasons) is the following:

void list_print(ostream& os, const sorted_list& list)

Now, your iteratornclass takes a mutable list, so this won't work as you expect. You will have quite a few methods to change to make this work.

In any case, your real problem is the lack of a proper copy-constructor. Right now, when you "copy" a list, both end up sharing the same elements, but your destructor is written as if each list owns it's own nodes. Define a proper copy operation and it will solve your problem.

More elaborate help on how to solve the problem: (untested)

Change signature:

void list_print(ostream& os, const sorted_list& list);

Declare + define copy constructor:

sorted_list::sorted_list (const sorted_list& other);

Change iteratorn interface to support a const sorted_list:

class sorted_list::iteratorn
{
public:
    iteratorn();
    ~iteratorn();
    iteratorn(const sorted_list& list);
    const list_link* list_begin() const;
    bool iterator_end() const;
    void iterator_next();
    int iterator_get_key() const;
    double iterator_get_value() const;

private:
        // You *should* make this `const` but it is not required.
    sorted_list::list_link* current;
};

As you can see, the changes are rather minimal, but need to be applied in various places.

const + non-const iterators:

I applied changes here based on the fact that your iteratorn was currently only defining read-only operations on your sorted_list. If you want to support write access to allow changing the value stored in list nodes (never allow changing the key or you won't have a sorted list anymore), you should define two iterator classes. See the STL iterator interface for more details.


You're copying the list by value, so the local copy in list_print() destructs at end of scope. Pass it by const-reference instead.

This in turn means you will have to change your sorted_list to support working with const lists. In particular you need to have a function that returns a const iterator pointing to the beginning of the list:

sorted_list::const_iteratorn begin() const
{
    // returns a const_iteratorn pointing at the beginning of this list
}

Notice you need a new kind of iterator: a const_iteratorn, which promises it won't change the list.

Then, inside print_list() initialize a const_iteratorn with the start iterator that sorted_list returns, by copy:

sorted_list::const_iteratorn s(list.begin());

Finally create a second iterator instance that initializes with an end iterator coming from a member function of sorted_list, similar to the begin() function. This will maintain the const-correctness in print_list().

sorted_list::const_iteratorn e(list.end());
while( s != e ) {       // two iterators should be able to compare
    // ...
    s.iterator_next();  // consider ++s
}

Also, as André mentioned, the fact you don't have a proper copy-constructor and assignment operator is a severe issue. Make sure that copying a sorted_list means copying all its elements, so that the new object owns its own list of elements. Do recall the Rule of Three.

0

精彩评论

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