delete []

  • Thread starter Jean-Marie Epitalon
  • Start date
J

Jean-Marie Epitalon

Hello,

please someone could explain to me why brackets are needed when deleting a
dynamic array, like :

int * my_array = new int[5];
...
delete [] my_array

Thanks
Jean
 
R

Rolf Magnus

Jean-Marie Epitalon said:
Hello,

please someone could explain to me why brackets are needed when deleting a
dynamic array, like :

int * my_array = new int[5];
...
delete [] my_array

Mostly because the language definition says so.
 
S

Salt_Peter

Jean-Marie Epitalon said:
Hello,

please someone could explain to me why brackets are needed when deleting a
dynamic array, like :

int * my_array = new int[5];
...
delete [] my_array

Thanks
Jean

Because a pointer to an array also stores how many elements are in the
primitive container.
In other words, my_array is both a pointer and it is related to an
element count.
And that element count (5) is hidden from you by the implementation.
So delete [] invokes magicly the correct number of d~tors.
 
A

Alf P. Steinbach

* Colander:
Hi There,
Jean-Marie Epitalon said:
Hello,

please someone could explain to me why brackets are needed when deleting a
dynamic array, like :

int * my_array = new int[5];
...
delete [] my_array

http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.11

Yes, but I think Marshall could have explained why.

The original motivation was the principle of not paying for what you
don't get. C++ needs to know the number of array elements in order to
call their destructors. And it's natural to implement C++ new in terms
of C malloc, but malloc may not be storing the element count itself: it
may in turn be using an OS allocator (say) that does that transparently,
with the count not available. So instead of requiring malloc to add an
extra array length field (i.e. allocate four or more bytes more than
actually requested), new[] does that and plain new doesn't. Which means
that delete[] must adjust (compensate) for the shenanigans of new[].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,368
Latest member
EwanMacvit

Latest Threads

Top