delete[] 是否释放由指向指针的指针分配的内存

发布于 2024-12-04 15:45:40 字数 221 浏览 0 评论 0原文

我有一个指向其他对象的指针数组,称为 Comparable* array(在类的模板内)。

据我了解,delete 删除指针引用的内存,而delete [] 则释放分配给数组中每个指针的内存。

我的问题是,如果我有一个包含指向其他对象的指针的数组,如何释放数组中每个指针引用的内存数组本身?

I have an array of pointers to other objects called Comparable* array (inside a template for a class).

I understand that delete deletes memory referenced by a pointer, and that delete [] deallocates the memory assigned to each pointer in an array.

My question is if I have an array that contains pointers to other objects, how do I deallocate the memory referenced by each pointer in the array and the array itself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

撑一把青伞 2024-12-11 15:45:40

如果我有一个包含指向其他对象的指针的数组,如何释放数组中每个指针和数组本身引用的内存?

您刚才描述的方式:)循环遍历数组以删除每个对象,然后删除数组:

for (int i = 0; i < n; ++i)
    delete array[i];
delete[] array;

if I have an array that contains pointers to other objects, how do I deallocate the memory referenced by each pointer in the array AND the array itself?

The way you just described :) Loop through the array to delete every object and then delete the array:

for (int i = 0; i < n; ++i)
    delete array[i];
delete[] array;
马蹄踏│碎落叶 2024-12-11 15:45:40

delete[] 为数组中的每个对象调用析构函数(如果存在这样的析构函数)。对于指针数组,delete[] 不会释放每个指针,因为指针是没有析构函数的普通类型。您需要删除代码中的每个指针。

delete[] calls destructor for every object in array, if such destructor exists. For array of pointers, delete[] does not release every pointer, since pointer is plain type without destructor. You need to delete every pointer in the code.

不寐倦长更 2024-12-11 15:45:40

您需要循环数组以释放数组索引引用的位置,并且需要在循环结束后释放数组本身。

注意:假设您已使用 new[] 动态分配

You need to loop over the array to deallocate the locations referenced by array indexes and need to deallocate the array itself at the end, after the loop.

Note: Assuming you have dynamically allocated using new[]

魔法少女 2024-12-11 15:45:40

不,事实并非如此。

delete[] 删除使用 new[] 分配的对象数组,而不是指针数组。

No, it doesn't.

delete[] deletes an array of objects allocated using new[], not an array of pointers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文