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.
if you do a non-array type:
T t = new T;
// ...
delete t;
It will know how much to delete because it knows how big a T is. If you do an array:
T t* = new T[10];
// ...
delete [] t;
It will lay down some extra info with the allocation to tell it how much to delete. Note, we use delete [] t
with the extra []
in there to tell it it's an array. If you don't do that it will think it's just a T
and only free that much memory.
Always use delete
if you use new
and free
if you use malloc
. new
does 2 things first it allocates the memory, then it constructs the object. Similarly delete
calls the destructor and then frees the memory. malloc\free
only deal with the memory allocation and deallocation.
In C++, a constructor is called using new, but not when using malloc. Similarly a destructor is called when using delete, but not when using free.
If you have new-ed an array using MyClass* x = new MyClass[25], then you need to call delete[] x, so that they system knows that it's deleting (and destructing) a group of objects instead of a single one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With