[C++]动态分配的重要性

[c++]The importance of dynamic allocation

本文关键字:重要性 动态分配 C++      更新时间:2023-10-16

我写了一个双向链表,并试图添加一个append()(在末尾插入)和len()(计算列表中的成员数量)。我只是不明白为什么它现在不起作用。这是最简单的代码:

#include<iostream>
using namespace std;
class linkedList{  
private:  
    struct node{  
        node* last;
        node* next;  
        char* str;  
    };  
    node sentinel;  
public:  
    linkedList();  
    ~linkedList();  
    int len();  
    void append(char*);  
};  
linkedList::linkedList(){  
    sentinel.last=&sentinel;  
    sentinel.next=&sentinel;  
    sentinel.str="I am sentinel!!";  
};  
linkedList::~linkedList(){};  
int linkedList::len(){  
    node* currentNode=&sentinel;  
    int count=0;  
    while ((*currentNode).next!=&sentinel){  
        count++;  
        currentNode=(*currentNode).next;  
        cout<<(*currentNode).str<<endl;  
    }  
    return count;  
}  
void linkedList::append(char* str){  
    node newNode;  
    newNode.str=str;  
    newNode.last=sentinel.last;  
    (*sentinel.last).next=&newNode;  
    sentinel.last=&newNode;  
    newNode.next=&sentinel;  
}  
int main(){  
    linkedList myList;  
    myList.append("Hello");  
    myList.append("World");  
    int length=myList.len();  
    cout<<length<<endl;  
    return 0;  
}  

我所做的只是将两个新节点添加到链表中,并计算我的节点总数。 它应该返回 2。 但是为什么它不起作用呢?

下面的代码中的newNode将在追加完成执行后立即超出范围。将其内存地址分配为指向更多全局成员的指针可能会以段错误结束。

void linkedList::append(char* str){  
    node newNode;  
    newNode.str=str;  
    newNode.last=sentinel.last;  
    (*sentinel.last).next=&newNode;  
    sentinel.last=&newNode;  
    newNode.next=&sentinel;  
}  

尝试使用 new node 在堆上分配节点,可能使用 shared_ptr 使内存管理更简单一些。

void linkedList::append(char* str){  
    node *newNode = new node;  
    newNode->str=str;  
    newNode->last=sentinel.last;  
    (*sentinel.last).next=newNode;  
    sentinel.last=newNode;  
    newNode->next=&sentinel;  
}

使用这种方法,请确保在销毁链接列表时通过每个节点上的delete运算符清理节点。

或者,考虑使用 shared_ptr 指向节点而不是原始指针,当 linkedlist(而不是其他人)指向节点时,原始指针将始终调用 delete

使用 new 关键字分配新节点:

void linkedList::append(char* str){  
    node *newNode = new node();  
    newNode->str=str;  
    newNode->last=sentinel.last;  
    (*sentinel.last).next=newNode;  
    sentinel.last=newNode;  
    newNode->next=&sentinel;  
}