动态内存能比得上全局变量吗?

Is dynamic memory comparable to global variables?

在一个链表中,我们这样声明node

struct node
{
    int data;          // Data part
    struct node* next; // pointer to next node

    node(int key)
    {
        data = key;
        next = NULL;
    } 
};

我们的插入函数看起来像这样

void insert(int key)
{
    struct node* go = head; // Head is global.
    while(go != NULL) 
    { 
        go = go -> next; 
    }
    go -> next = new node(key);
}

如果函数insert实际上返回的是void,那么它是如何改变链表的呢?

运算符 new 分配的内存(来自自由存储区)是否像全局变量一样?

new 不像全局变量。在 C++ 中,全局变量(假设您不谈论全局指针)在您的应用程序入口点 "main" 被调用之前分配,并在您的应用程序关闭时释放。

另一方面,new 在调用时分配新内存,在调用 delete 时释放内存

MyClass* c = new MyClass(); // Allocate
// ..
delete c; // Deallocate, MyClass c is deleted

因此,如果您使用 new 创建了一些对象,并且永远不要删除它。它会一直存在,但你可能会丢失指向分配数据的指针并导致内存泄漏。