Operator New
Operator to dynamically allocate memory and construct data of a specified type.
Syntax
`
Declare Operator New ( size As UInteger ) As Any Ptr
Declare Operator new[] ( size As UInteger ) As Any Ptr
`
Usage
`
result = New datatype
or
result = New datatype ( initializers, ... )
or
result = New datatype[ count ]
`
Parameters
`size`
Number of bytes to allocate.
`initializers`
Initial value(s) for the variable.
`datatype`
Name of the data type to create.
`count`
Exact number of elements to allocate.
Return Value
A pointer of type datatype to the newly allocated data.
Description
The `New` operator dynamically allocates memory and constructs a specified data type. For simple types, like integers, an initial value can be given. For types without constructors, initial values can be specified for each field. Types that have constructors can have their constructors called by `New` as well. If no initializers are given, the default values for those types will be set.
`New[]` is the array-version of the `New` operator and allocates enough memory for the specified number of objects. The default constructor for the type will be used to set the initial values for each item.
The `New` and `New[]` operators cannot be directly used with `String`, but work with `Udt`s containing strings.
Objects created with `New` must be freed with `Delete`. Memory allocated with `New[]` must be freed with `Delete[]`, the array-version of `Delete`. You cannot mix and match the different versions of the operators.
Specifying an initial value of `Any`, as in `new datatype(any)` will allocate memory for the type, but not initialize the data. This is only valid on data types that do not have constructors.
Specifying an initial value of `Any`, as in `new datatype[count]{any}` will allocate memory for the array, but not initialize the data. This is only valid on data types that do not have constructors.
Example
`
Type Rational
As Integer numerator, denominator
End Type
Scope
' Create and initialize a "rational" and store its address.
Dim p As Rational Ptr = New Rational(3, 4)
Print p->numerator & "/" & p->denominator
' Destroy the rational and give its memory back to the system.
Delete p
End Scope
Scope
' Allocate memory for 100 integers and store the address of the first one.
Dim p As Integer Ptr = New Integer[100]
' Assign some values to the integers in the array.
For i As Integer = 0 To 99
p[i] = i
Next
' Free the entire integer array.
Delete[] p
End Scope
`
Dialect Differences

- Only available in the -lang fb dialect.

Differences from QB

- New to FreeBASIC

See also

- `Delete`
- `Placement New`