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

标签 c++ c++11 linked-list c++14 delete-operator

所以我用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

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

#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 的值赋给 head。

但是如果像你说的那样在++size后面加上delete,head会指向被删除的东西。

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

您可能想使用 smart pointers以避免访问已删除的内存和内存泄漏。

关于c++ - 与 c++ 中的删除功能混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45335324/

相关文章:

c - 循环链表中的删除函数,当只剩下一个节点时,将下一个和上一个更改为空

java - 如何使 Java 中的自定义泛型类型链表排序?

c++ - 使用 constexpr 查找表

c++ - QFile/QDataStream 写入现有数据

C++ - 整个程序持续时间的单个本地类实例

c++ - 链表的复制版本溢出

c++ - 使 boost::fast_pool_allocator 与可变参数模板一起工作 (emplace)

c++ - 向条件语句添加条件

c - 函数,链表。将一个链表复制到另一个链表

c++ - 正确初始化成员引用