[fpc-pascal] Management operators question

Ryan Joseph ryan at thealchemistguild.com
Fri May 25 12:19:14 CEST 2018


Talking about dynamic arrays I was just curious if we could us the new management operators to make dynamic arrays that are managed on the stack.

Here’s a quick demo I typed up but I don’t understand why the init/dealloc count isn’t balanced. Calling the constructor seems to be the culprit, but why?    

type
	generic TDynArray<T> = record
		private type TDynArrayTable = array[0..0] of T;
		private type TDynArrayTablePtr = ^TDynArrayTable;
		private
			table: TDynArrayTablePtr;
		public
			constructor Create (values: array of T);
			procedure Push(value: T);
			class operator Finalize(var a: TDynArray);
			class operator Initialize(var a: TDynArray);
	end;

constructor TDynArray.Create (values: array of T);
var
	value: T;
begin
	for value in values do
		Push(value);
end;

class operator TDynArray.Initialize(var a: TDynArray);
begin
	writeln('init');
	a.table := nil;
end;

class operator TDynArray.Finalize(var a: TDynArray);
begin
	FreeMem(a.table);
	a.table := nil;
	writeln('dealloc');
end;

procedure TDynArray.Push(value: T);
begin
	if table = nil then
		table := GetMem(0);
	writeln('push ', value); // grow array etc...
end;

procedure TestDynArray;
type
	TIntArray = specialize TDynArray<Integer>;
var
	d: TIntArray;
begin
	d := TIntArray.Create([1, 2, 3]);
	d.Push(100);
end;

========

init
init
dealloc
push 1
push 2
push 3
push 100
dealloc
dealloc




Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list