[fpc-pascal] Managed properties idea

Ryan Joseph ryan at thealchemistguild.com
Thu Oct 5 04:30:45 CEST 2017


Yesterday when I was thinking about that enumerators I had an idea for a language feature and something which I saw introduced in Objective-C some years ago.

Retaining of a member variable through a property is a common pattern I do everyday nearly. In my root class I manage a simply retain count which frees the object when it reaches 0. When assigning variables that the receiver wants to take ownership of on assignment I have to make an accessor which manages the retain count of the object (boring boiler plate).

Consider the example below where the root class (TObject) overrides a class function which performs this retain count management (ManageObject). In the other class there is a member of type TObject which TMyClass will take ownership of when assigned. If the property “Data” includes the “managed” keyword the compiler will automatically call ClassType.ManageObject() and take the return value as the variable which is written to “m_data”.

I’ve been wanting to learn how to contribute to the compiler for years now but maybe this is an easy enough project to start with. I don’t know if this is  a problem people have though but I assume it may be since Objective-C had a system like for memory management and properties. What do you think? How do most FPC programmers handle memory these days?

type
	TObject = class
		class function ManageObject (obj: pointer): TObject; override;	
	end;

type
	TMyClass = class (TObject)
		private
			m_data: TObject;
		public
			property Data: TObject read m_data write m_data; managed;
			// if there’s a write method defined the compiler calls ManageObject before the write method
			property MyData: TObject read m_data write SetData; managed;
	end;

class function TObject.ManageObject (obj: pointer): TObject; override;
begin
	if obj <> nil then
		result := TObject(obj).Retain;
	else
		begin
			TObject(obj).Release;
			result := nil;
		end;
end;

Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list