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

Сайт ПДСНПСР. Если ты патриот России - жми сюда!


Знаете ли Вы, как разрешается парадокс Ольберса?
(Фотометрический парадокс, парадокс Ольберса - это один из парадоксов космологии, заключающийся в том, что во Вселенной, равномерно заполненной звёздами, яркость неба (в том числе ночного) должна быть примерно равна яркости солнечного диска. Это должно иметь место потому, что по любому направлению неба луч зрения рано или поздно упрется в поверхность звезды.
Иными словами парадос Ольберса заключается в том, что если Вселенная бесконечна, то черного неба мы не увидим, так как излучение дальних звезд будет суммироваться с излучением ближних, и небо должно иметь среднюю температуру фотосфер звезд. При поглощении света межзвездным веществом, оно будет разогреваться до температуры звездных фотосфер и излучать также ярко, как звезды. Однако в дело вступает явление "усталости света", открытое Эдвином Хабблом, который показал, что чем дальше от нас расположена галактика, тем больше становится красным свет ее излучения, то есть фотоны как бы "устают", отдают свою энергию межзвездной среде. На очень больших расстояниях галактики видны только в радиодиапазоне, так как их свет вовсе потерял энергию идя через бескрайние просторы Вселенной. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМАФорум Рыцари теории эфира
Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research Institution home page

Боровское исследовательское учреждение - Bourabai Research Bourabai Research Institution