简体   繁体   English

数组在内存中是如何存储和删除的?

[英]How are arrays stored and deleted in memory?

I made a 2D array on the heap of some objects:我在一些对象的堆上做了一个二维数组:

Step (1)第1步)

Obj **arr = new Obj *[n];

for (int i=0;i<n;i++)
{
    arr[i] = new Obj[n];
}

// so this creates 2D arr[n][n]...then when I delete it: // 所以这会创建 2D arr[n][n]...然后当我删除它时:

Step (2)第2步)

for (int i=0;i<n;i++)
{
    delete [] arr[i];
}
delete [] arr;

So I'm still not sure what this delete does.所以我仍然不确定这个删除有什么作用。 Does it run the destructor of Obj and flag the OS telling it this is now available memory.它是否运行 Obj 的析构函数并标记操作系统告诉它现在有可用内存。

Now what I REALLY do not understand is that when I do Step (1) again (after I deleted), I get these objects initialized to weird values, yet this doesn't happen the first time I do it (all zero-initialized).现在我真正不明白的是,当我再次执行步骤 (1) 时(在我删除之后),我将这些对象初始化为奇怪的值,但这在我第一次执行时不会发生(全部为零初始化) . Did I just get lucky the first time?我只是第一次走运吗?

Your example lacks the declaration of Obj.您的示例缺少 Obj 的声明。

  • new[] allocates memory and calls the constructor of each element new[] 分配内存并调用每个元素的构造函数
  • If the constructor does not alter memory, you will see some random values - maybe zeros.如果构造函数不改变内存,您将看到一些随机值 - 可能为零。
  • delete[] calls the destructor of each element previously allocated with new[] and deallocates the memory, finally. delete[] 调用先前用 new[] 分配的每个元素的析构函数,最后释放内存。
  • In a debugging compilation the memory might be filled with some bytes indicating the deallocation.在调试编译中,内存可能会填充一些指示释放的字节。
  • Doing new[] right after the deallocation might show indicator bytes.在解除分配后立即执行 new[] 可能会显示指示符字节。

AFAIK, the following code will NOT give you weird values, no matter how many times you repeat deleting and newing. AFAIK,无论您重复删除和新建多少次,以下代码都不会为您提供奇怪的值。

#include <iostream>
using namespace std;

class Foo
{
public:
    Foo(): val(-2) { cout << "ctor" << endl; }
    ~Foo() { cout << "dtor: " << val << endl; }

private:
    int val;
};

int main()
{
    Foo **arr = new Foo *[2];
    for (int i = 0; i < 2; ++i)
        arr[i] = new Foo[2]();    // <- for builtin type, () is required to initialized to zero.

    for (int i = 0; i < 2; ++i)
        delete [] arr[i];
    delete [] arr;
    return 0;
}

Relevant post: Operator new initializes memory to zero相关帖子: Operator new 将内存初始化为零

As to what happens to pointers after you delete them, please see this post: C - What happens to an array of pointers when the array is freed?至于删除指针后会发生什么,请参阅这篇文章: C - 当数组被释放时,指针数组会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM