C++ 何时使用 delete[] 并正确释放内存?

C++ when to use delete[] and properly deallocate memory?

所以我看到有内存管理功能的配对,例如 malloc/freenew/deletenew[]/delete[],但有时您并不总是调用 newnew[] 并且您仍然需要调用 deletedelete[]free。例如,strdup 就是这样一个函数,它封装了内存分配,您以后仍然需要自己解除分配该内存。

那么,如果您不总是在某种意义上写 newmalloc,您什么时候知道释放内存?我特别好奇deleting arrays of objects. Just simple arrays. Because, that seems to be one of the use cases that delete[] is made for. (I'm looking at cplusplus.)

那么,这有效吗?这是必要的吗?有什么遗漏吗?

unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF};
for(int i = 0; i < 4; i++) 
    std::cout << std::hex << +bytes[i];
delete[] bytes;

bytes 在技术上是 unsigned char * 类型,对吧?我知道我在技术上有一个指针,但因为这不是一个对象数组,所以我不确定它是否会自动销毁。

不,这是无效的。

delete[] 的每次调用都应与 new[] 配对。如果它没有配对(例如 strdup),那是因为某些函数在内部调用 malloc/new[].

unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF}; 堆栈 上声明了 4 个字节的内存。堆栈内存在封闭 scope 结束时自动销毁。它们与函数调用所需的内存共享相同的内存。

new/delete 分配和释放 heap 内存。堆内存没有特定的获取或销毁顺序(不同于 堆栈 ,即 first-in-last-out),因此您必须显式地 delete 它,否则程序将不会'不知道什么时候释放它。

C++ when to use delete[] and properly deallocate memory?

当内存是用 new[] 分配的内存并且该内存尚未被释放,并且不会被其他任何人释放时。

So, is this valid?

无效。您所展示的内容具有未定义的行为。您不能取消分配自动变量。您不能对未分配给 new[] 的任何内容调用 delete[]

Is this necessary?

没有必要。 自动 变量被销毁......当它们超出范围时自动销毁。

bytes is technically an unsigned char * type, right?

I know I technically have a pointer

不对。 bytes 在所有方面都是一个数组。不是指针。

So is C++ different from C in that regard about pointers to arrays?

没有区别。数组也是 C 中的数组。

您可能对数组衰减感到困惑。当在值上下文中使用时,数组名称将衰减为指向第一个元素的指针。数组衰减成的指针是指针,而数组不是。示例:

int  arr[4] = {1, 2, 3, 4}; // an array
int* ptr  = arr;            // a pointer; arr decays and is assignable to a pointer
int* ptr2 = &arr[0]         // decaying is syntactic sugar for this
int size1 = sizeof arr;     // size of the array == sizeof(int)*4
int size2 = sizeof ptr;     // size of the pointer == sizeof(int*)

此外,在函数参数列表中,数组声明与指针声明相同。这非常令人困惑。你只需要记住数组不能按值传递,所以数组作为函数参数必须有其他含义。

void foo(int[4]); // confusing
void foo(int*);   // actually means this