与 c++ 中的删除功能混淆

Confusion with delete functionality in c++

本文关键字:功能 删除 c++      更新时间:2023-10-16

所以我用 c++ 编写了这段代码

#include "ContactBook.hpp"
int main(){
std::string name;
ContactList *cl1 = new ContactList();
while(true){
std::cout << "Enter a name or press Q to quit" << std::endl;
std::cin >> name;
if(name=="Q"||name=="q")
break;
else{
cl1->addToHead(name);
}
}
cl1->print();
delete cl1;
return 0;
}

我的头文件定义 ->

#ifndef ContactBook_hpp
#define ContactBook_hpp
#include <iostream>
class Contact{
friend std::ostream &operator<<(std::ostream &os, const Contact &c);
friend class ContactList;
public:
Contact(std::string name);
private:
std::string name;
Contact* next;
};
class ContactList{
public:
ContactList();
void addToHead(const std::string &name);
void print();
private:
Contact *head;
static int size;
};
#endif

现在这是我的头文件函数定义。 联系人列表和联系人是两个类。联系人列表是联系人的好友类。

#include "ContactBook.hpp"
Contact::Contact(std::string name){
this->name = name;
next = NULL;
}
std::ostream &operator<<(std::ostream &os, const Contact &c){
os << "Name: " << c.name << std::endl;
return os;
}
ContactList::ContactList():head(NULL){};
int ContactList::size = 0;
void ContactList::addToHead(const std::string &name){
Contact *newOne = new Contact(name);
if(head==NULL){
head = newOne;
}
else{
newOne->next = head;
head = newOne;
}
++size;
}
void ContactList::print(){
Contact *temp;
temp = head;
while(temp!=NULL){
std::cout << *temp;
temp = temp->next;
}
}

问题是每当我添加时

delete newOne;

在 addToHead 定义中的第三个代码片段中的 ++size 之后。

我最终在奇数输入的名称上得到了一个无限循环(除了 1(!我只是不明白为什么会发生这种情况!:D,这方面的一些知识将不胜感激!

在这里,在你的addToHead中:

Contact *newOne = new Contact(name);
if(head==NULL){
head = newOne;
}
else{
newOne->next = head;
head = newOne;
}
++size;

可以这样写:

Contact *newOne = new Contact(name);
newOne->next = head; // if (head==NULL) newOne->next=NULL else newOne->next=head;
head = newOne;
++size;

您将 newOne 的值分配给标题。

但是如果你添加删除,就像你说的,在++size之后,head会指向被删除的东西。

打印方法中发生的情况是取消引用已删除的内容。 取消引用已删除的内容时发生的情况是未定义的行为,这可能会导致奇怪的输出或崩溃。

您可能希望使用智能指针来避免访问已删除的内存和内存泄漏。