'New []' documentation page wrote:
The total memory, in bytes, to be allocated with 'New datatype[count]' expression is calculated as 'sizeof(datatype) * count', plus 'sizeof(uinteger)' if there is an implicit or explicit Destructor. The total memory requested in bytes to be allocated must not overflow the value that can be held by a 'UInteger'. The extra uinteger, if allocated, stores the number of elements as part of the allocation, so that 'Delete []' Statement can determine the count of destructors to call.
To clarify the operation of
'New []' under the hood, an emulation of
'New []' with
'Allocate', being compatible with the call of
'Delete []' at the end:
Code: Select all
Type UDT
Dim As Integer N
Declare Constructor (Byval I As Integer = 0)
Declare Destructor ()
End Type
Constructor UDT (Byval I As Integer = 0)
Print "Constructor"
This.N = I
End Constructor
Destructor UDT ()
Print "Destructor"
End Destructor
Dim As Integer N = 3
'---------- Version with 'Allocate' using, compatible with 'Delete []' at end ----------
'there is destructor:
Dim As Uinteger Ptr p10 = Allocate(Len(Uinteger) + N * Len(UDT))
p10[0] = N
Dim As UDT Ptr p1 = Cptr(UDT Ptr, p10 + 1)
'or if there was no destructor:
'Dim As UDT Ptr p1 = Allocate(N * Len(UDT))
For I As Integer = 0 To N - 1
'there is constructor:
p1[I].Constructor(I + 1)
'or if there was no constructor:
'p1[I] = Type(I + 1)
Next I
Print p1
For I As Integer = 0 To N - 1
Print p1[I].N,
Next I
Print
Delete [] p1
Print
'---------- Version with 'New []' / 'Delete []' ----------
Dim As UDT Ptr p2 = New UDT[N]
Print p2
For I As Integer = 0 To N - 1
p2[I].N = I + 1
Next I
For I As Integer = 0 To N - 1
Print p2[I].N,
Next I
Print
Delete [] p2
Print
Sleep
Output:
Code: Select all
Constructor
Constructor
Constructor
1776584
1 2 3
Destructor
Destructor
Destructor
Constructor
Constructor
Constructor
1776584
1 2 3
Destructor
Destructor
Destructor
Note: As the addresses of the 2 dynamically allocated objects are identical, it proves that the first object allocated using 'Allocate' has well been deallocated by 'Delete []'.