delete[] 是否释放由指向指针的指针分配的内存
我有一个指向其他对象的指针数组,称为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您刚才描述的方式:)循环遍历数组以删除每个对象,然后删除数组:
The way you just described :) Loop through the array to delete every object and then delete the array:
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.
您需要循环数组以释放数组索引引用的位置,并且需要在循环结束后释放数组本身。
注意:假设您已使用
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[]
不,事实并非如此。
delete[]
删除使用new[]
分配的对象数组,而不是指针数组。No, it doesn't.
delete[]
deletes an array of objects allocated usingnew[]
, not an array of pointers.