我一直在编写一组整数 ADT 的链表实现,并且在编译和运行代码时遇到了双重释放或损坏错误,而对于我的生活,我无法弄清楚源代码。我最初认为它在析构函数中,但在我对其进行了相当多的修改后,这似乎不是问题。我附上我的代码以供审查。
class list_intset: public intset {
struct node {
int number;
node *next;
node(int n, node * n2 = NULL):number(n),next(n2){}
};
mutable node * head;
int set_size;
list_intset(const list_intset & a) { //copy constructor thing
throw std::domain_error("No copy constructor ");
}
list_intset & operator =(const list_intset & a){ //= sign operator
throw std::domain_error("No = for intset");
}
//
public:
list_intset(){ //default constructor that constructs the empty set
set_size = 0;
head = NULL;
};
virtual ~list_intset(){ //virtual devastator
node * temp;
while(head != NULL){
temp = head->next;
delete head;
head = temp;
}
};
// //basic operations
void add(int a){ //add an item to the set
head = new node(a, head);
++set_size;
}
//
void remove(int a){ //removes an item from the set //ask professor about this one, I'm not so sure
node * temp;
node * ptr = head;
while(ptr && ptr->number != a){
ptr = ptr->next;
}
if(ptr != NULL){
temp = ptr;
ptr = ptr->next;
cout << "deleting temp in remove."<<endl;
delete temp;
}
}
void do_clear(node * n){
if(n != NULL){
do_clear(n->next);
cout << "deleting n in do_clear."<<endl;
delete n;
}
}
void clear(){ //removes all elements from the set
do_clear(head);
set_size = 0;
}
//
bool contains(int a) const{ //returns true if an element is in the set, returns false if it is not.
node * temp_head = head;
bool flag = false;
while(temp_head != NULL){
if(temp_head->number == a){
flag = true;
break;
}else{
temp_head = temp_head->next;
}
}
return flag;
}
int size() const{ //returns how many elements are in the set
cout << "size" << endl;
return set_size;
}
void display(std::ostream & a) const{ //displays all of the elements in a set with the curly brackets, ex: {2 3 4 7 9}
node * temp = head;
cout << "display" << endl;
a << "{";
for(int i = 0; i < set_size; i++){
a << temp->number << " ";
temp = temp->next;
}
a << "}";
}
我省略了我编写的集合操作函数,因为我没有在这些函数中进行任何删除。此外,我用来尝试跟踪运行和编译期间的错误的 cout 语句,例如“删除临时删除”。
谢谢,大卫