Operator Placement New
Operator to construct an object at a specified memory address.
Syntax
`
result = New(address) datatype
or
result = New(address) datatype ( initializers, ... )
or
result = New(address) datatype[ count ]
`
Parameters
`address`
the location in memory to construct. the parenthesis are not optional.
`initializers`
Initial value(s) for the variable.
`datatype`
name of the data type to construct.
`count`
Number of elements to construct.
Return Value
A pointer of type `datatype` to the newly constructed data.
Description
The `Placement New` operator constructs a specified data type at the specified memory location.
The `Placement New` operator cannot be directly used with `String`, but works with `Udt` containing string.
For simple types, like integers, an initial value can be given. For types without `Constructor`s, initial values can be specified for each field. Types that have constructors can have their constructors called by `Placement New` as well. If no initializers are given, the default values for those types will be set.
Memory is not allocated when using the `Placement New` operator. Instead, the memory at the specified `address` is used.
It is incorrect to call `Delete` on the address (otherwise, the memory is deallocated). The proper way is to only call the destructor (with syntax as for a member method, using member access operator).
See examples below for proper placement new usage.
Specifying an initial value of `Any`, as in `New(address)datatype(Any)` or `New(address)datatype[count]{Any}` will not initialize the data. This is only valid on data types that do not have constructors.
Example
`
'' "placement new" example
Type Rational
As Integer numerator, denominator
Declare Destructor ( )
End Type
Destructor Rational ( )
End Destructor
Scope
'' allocate some memory to construct as a Rational
Dim As Any Ptr ap = CAllocate(Len(Rational))
'' make the placement new call
Dim As Rational Ptr r = New (ap) Rational( 3, 4 )
'' you can see, the addresses are the same, just having different types in the compiler
Print ap, r
'' confirm all is okay
Print r->numerator & "/" & r->denominator
'' destroying must be done explicitly, because delete will automatically free the memory
'' and that isn't always okay when using placement new. ALWAYS explicitly call the destructor.
r->Destructor( )
'' we explicitly allocated, so we explicitly deallocate
Deallocate( ap )
End Scope
`
Dialect Differences

- Only available in the -lang fb dialect.

Differences from QB

- New to FreeBASIC

See also

- `Delete`
- `New`