C ++中的删除如何知道要删除多少内存位置 [英] How does the delete in C++ know how many memory locations to delete
问题描述
删除操作如何工作?是更好然后free()?如果u ptr = new char [10]
,那么使用 delete ptr
delete
code> free 仅作为函数存在。在C ++下,鼓励使用 new
/ delete over malloc c $ c> / free()
。
删除操作符中的内部魔术。当使用 new []
创建数组时,数组的大小存储在内存块的元数据中。 delete []
使用该信息。
这些当然是编译器,和实现依赖。
how does the delete operator work? Is it better then free()?. Also if u do ptr=new char[10]
, then delete using delete ptr
, how does the pointer know how many locations to delete.
解决方案 There is only delete
operator, free
exist only as function. Under C++, you are encouraged to use new
/delete
over malloc()
/free()
.
There is an internal "magic" in delete operator. When an array is created with new[]
, the size of array is stored in the metadata at the memory block. delete[]
makes use of that information.
All this is of course compiler-, OS-, optimizer- and implementation-dependent.
这篇关于C ++中的删除如何知道要删除多少内存位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!