project1.lpr(1,6) Error: Syntax error, "BEGIN" expected but "identifier DATAO" found
It doesn't compileyou have advanced syntax turned offQuoteproject1.lpr(1,6) Error: Syntax error, "BEGIN" expected but "identifier DATAO" found
project1.lpr(24,6) Error: Pointer type expected, but got "datao"
project1.lpr(25,5) Error: Illegal qualifier
project1.lpr(27,11) Error: Pointer type expected, but got "datao"
constructor is just for initialization purpose. Memory is automatically allocated (and freed) within stack by definition of a record variable, which is different from objects' construction which allocates memory within heap area.Initialization on advanced records can be done through the Initialize class operator too.
Quoteproject1.lpr(24,6) Error: Pointer type expected, but got "datao"
project1.lpr(25,5) Error: Illegal qualifier
project1.lpr(27,11) Error: Pointer type expected, but got "datao"
Read the manual: https://www.freepascal.org/docs-html/ref/refse61.html#x120-1440009.1 (https://www.freepascal.org/docs-html/ref/refse61.html#x120-1440009.1) - " Constructors or destructors cannot be defined."
Initialization on advanced records can be done through the Initialize class operator too.Thank you for that, i did not knew that too!
Why not using more simply a class ?Because a record, as soon as out of scope, produce no memory leaks. At least thats how i learned it.
Note you can also have automatic finalize, see: https://wiki.freepascal.org/management_operators#FinalizeWow, that is crazy cool!!! Will use both in my next projects since i also do like records a lot (not like above code, more the simple ones where i need initialization, and now with finalization it really rocks to clean up my stuff, even if not needed)
This is how to write it with the implicit initialize/finalize. You may still want to add the explicit constructor:
{$mode objfpc}{$modeswitch advancedrecords} // or simply only {$mode delphi} type pdatao= ^datao; datao = record Data: Pointer; constructor init(size:PtrUint); Class operator initialize(var rec:datao); Class operator finalize(var rec:datao); end; constructor datao.init(size:ptrUint); begin Data := ReAllocMem(Data,size); // realloc, because initialize has already allocated data. end; class operator datao.initialize(var rec:datao); begin rec.Data := AllocMem(250); writeln('At initialization 250 bytes allocated for data'); end; class operator datao.finalize(var rec:datao); begin FreeMem(Rec.Data); writeln('At finalization, data is free''d'); end; var d: pdatao; begin New(d); Dispose(d); end.
This is how to write it with the implicit initialize/finalize. You may still want to add the explicit constructorThanks a lot for your snippet!
As it is, I discovered a bug that caused a double free if you call dispose instead of freemem because data should be set to nil after the call to freemem.Dispose call Finalize, FreeMem not.