[fpc-pascal] Auto vars (again)

Ryan Joseph ryan at thealchemistguild.com
Sat Aug 18 01:24:05 CEST 2018


I had some free time recently so I decided as a learning experience to fork the compiler and implement the “auto var” idea that was mentioned a few weeks ago.

What I found is that it’s a pretty lightweight (in terms of impact on the compiler) and unintrusive way to manage memory on a per-scope basis which solves a minor but common pattern. This was highly debated but I know from my personal experience I often know at the time of declaring a class that I will allocate the class at the top of the function and free at the end. If this was C++ I would declare the class on the stack but we don’t have that option in Pascal so we’re forced into either a class or record paradigm. The better option would probably be full blown ARC but I don’t know if that’s ever going to be on the agenda of FPC.

I understand there’s lots of potential problems like passing an auto var out of scope, classes with constructors that require parameters (rather big problem) or perhaps the “auto” modifier (I did that because it was easy to parse) but is there any merit to this idea if it was cleaned up and made safe? I did some tests to see if you could prevent passing auto vars out of scope and it’s possible to prevent most ways but not 100%.

========================================================

program auto_test_1;

type
	TMyClass = class
		data: TObject; auto;
	end;

var
	obj: TMyClass; auto;
begin
	// obj is auto so TMyClass.Create is called along with subsequent auto var members
	writeln('obj:', obj.classname);
	writeln('data:', obj.data.classname);
	// when TMyClass.Free is called auto var members call Free also
end.

program auto_test_2;
uses
	fgl;

var
	list: specialize TFPGList<integer>; auto;
	i: integer;
begin
	// list is auto so TFPGList<integer>.Create is called
	// TFPGList as an auto var is a compelling alternative to dynamic arrays
	list.Add(1);
	list.Add(2);
	list.Add(3);
	for i in list do
		writeln(i);
end.


Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list