与 c++ 中的删除功能混淆
Confusion with delete functionality in c++
所以我用 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会指向被删除的东西。
打印方法中发生的情况是取消引用已删除的内容。 取消引用已删除的内容时发生的情况是未定义的行为,这可能会导致奇怪的输出或崩溃。
您可能希望使用智能指针来避免访问已删除的内存和内存泄漏。
相关文章:
- 在Qt5中使用QTextSteam时的"使用已删除功能"
- 链表删除功能的单指针 // 是可能的
- 删除功能不适用于串行通信后多个循环中的多个实例
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 使用删除功能?
- Sinlge 链表,C++,删除所有和搜索功能的问题
- 如何实现删除数组的功能?
- 使用已删除的功能unique_ptr
- C++使用已删除的功能与unique_ptr,make_unique
- 错误:当我尝试使用引用时,使用已删除的功能
- 二叉搜索树 - 使用 Linux 在虚拟机中制作删除功能
- 为什么我的删除功能总是出现分段错误
- C++链表删除和删除返回功能
- 与 c++ 中的删除功能混淆
- 启用 C++17 中已删除的功能
- C++:提升 ptree 删除子项:无匹配功能
- 用户使用C++中的删除功能删除文件
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- 为什么我的打印功能之一删除节点
- 功能删除在我第二次激活它时不起作用