[fpc-pascal] Custom NewInstance allocator

Sven Barth pascaldragon at googlemail.com
Tue Jun 4 14:06:33 CEST 2024


Hairy Pixels via fpc-pascal <fpc-pascal at lists.freepascal.org> schrieb am
Di., 4. Juni 2024, 10:54:

> In the manual it at https://www.freepascal.org/docs-html/ref/refse38.html
> it says "Calling the constructor will provoke a call to the virtual class
> method NewInstance, which, in its default implementation, calls GetMem, to
> allocate enough space to hold the class instance data, and then zeroes out
> the memory."
>
> I'm trying this like below but it crashes. Is this correct? The fact
> NewInstance returns TObject instead of Pointer doesn't make sense to me and
> suggests this isn't correct.
>
>   class function TDataObject.NewInstance: TObject;
>   begin
>     result := TObject(GetMem(InstanceSize));
>   end;
>

You also need to call TObject.InitInstance() on the allocated memory (that
should probably be mentioned in the documentation...).

Regards,
Sven

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20240604/a8f1be06/attachment.htm>


More information about the fpc-pascal mailing list