I was watching a youtube series about data structures and how to made our-self data structure.
But then the Instructor replaced the new[]
with ::operator new()
and delete[]
with ::operator delete()
, is there any difference? cuz this is the first time for me to see the ::operator
thing in c++
The new-expressions new T
and new T[n]
create objects in memory that they acquire.
The delete-expressions delete p
and delete [] p
destroy objects and release the memory where they were stored.
operator new
is a memory allocation function, and operator delete
is a memory deallocation function. They do not do anything more than manage memory, and correspond to C's malloc
and free
.
They have those names in order to avoid introducing more keywords to the language – "operator new" and "operator delete" are just funky ways of spelling "allocate" and "deallocate".
The ::
is the scope resolution operator and makes sure that these calls are specifically to the functions defined in the global scope.
The new-expressions and delete-expressions are not equivalent to these functions, but use them behind the scenes for memory management.
If you use operator new
for allocating memory you must then also create an object in that memory, and if you release memory with operator delete
you should first destroy the object that occupies the memory.