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.
`size`
number of bytes to allocate.
`initializers`
Initial value(s) for the variable.
`datatype`
name of the data type to create.
`count`
Number of elements to allocate.
Return Value
A pointer of type datatype to the newly allocated data.
Description
The `Placement New` operator constructs a specified data type at the specified memory location.
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 `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. See examples below for proper placement new usage.
Specifying an initial value of `Any`, as in `new(address) datatype(any)` will 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(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
End Type
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`