c++ - 动态内存可以与全局变量相媲美吗?

标签 c++ data-structures linked-list

链表中,我们声明节点如下:

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 创建某个对象,并且永远不会删除它。它会一直存在,但您可能会丢失指向已分配数据的指针并导致内存泄漏。

关于c++ - 动态内存可以与全局变量相媲美吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847485/

相关文章:

c++ - typedef'ing 结构对自身的影响是什么?

c++ - 实现接口(interface)的类的析构函数在引用为接口(interface)时未调用

c++ - C++ 中的 std::map 键

c++ - c++中类集合数据结构是什么

java - 比较存储为 List 结构的 Hashmap 值

c# - 链表与列表<T>

c - 删除链表中的节点

c++ - 在网络服务器和 UTF-8 上运行的 C++ 程序的文本输出

java - 相反的方法不执行任何堆栈操作

algorithm - 比较包含集合的列表部分的高效算法