Is there any means to access the length before deleting the array?
No. there is no way to determine that.
The standard does not require the implementation to remember and provide the specifics of the number of elements requested through new
.
The implementation may simply insert specific bit patterns at end of allocated memory blocks instead of remembering the number of elements, and might simply lookup for the pattern while freeing the memory.
In short it is solely an imlpementation detail.
On a side note, There are 2 options to practically overcome this problem:
-
You can simple use a
std::vector
which provides you member functions like size()
or
-
You can simply do the bookkeeping yourself.
new
atleast allocates enough memory as much as you requested.
You already know how much memory you requested so you can calculate the length easily. You can find size of each item using sizeof
.
Total memory requested / Memory required for 1 item = No of Items
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…