Quote
Dave Shapiro wrote:
> Say I have a class, TSomeClass which has a method SomeMethod which acts
> on another TSomeClass and returns, oh, an Integer. If I do this
> var
> I: Integer;
> begin
> I := (TSomeClass.Create).SomeMethod(TSomeClass.Create);
> end;
> Have I just orphaned memory? That is, I anonymously created two
> instances of TSomeClass, and since I didn't assign them to variables, I
> can't destroy them. Does the compiler do the destroying for me? How does
> it know which destructor to call? Does it just assume to call the
> virtual destructor Destroy from TObject?
If you create it, you must free it. (The only exception is when you
create a control and then tell another control "Here, you own this" -
owned controls are freed whenever their owner is freed. Even here, it
can't hurt to free a control you create.)
There are a number of ways that you can do this.
(1) You can, of course, do something like "ThisInstance :=
TSomeClass.Create" and then, later, "ThisInstance.Free".
(2) You can use a "with" statement - "with TSomeClass.Create do begin
SomeMethod; Free; end" - though this won't work so well in this case,
where you want to also create an anonymous object and pass it as a
parameter.
(3) In D3, you can use interfaces. If TSomeClass implements IConsumer
and and IConsumable, you can rewrite your code as
Quote
> I := (TSomeClass.Create as IConsumer).SomeMethod( TSomeClass.Create
> as IConsumable);
Interface tables are reference counted, just like huge strings. When you
pass the IConsumable reference to SomeMethod, it gets 'assigned' to the
formal parameter, thus setting the reference count to 1. When the
function returns, the formal parameter goes out of scope, the reference
count goes to 0, and the object is freed. Similarly for the IConsumer
objects 'assignment' to Self.
(4) Most egregiously, you could write TSomeClass.SomeMethod to both Free
Self and it's TSomeClass parameter. This is bad in at least two ways:
(A) objects are not being freed by the creating code. This makes the
code hard to follow and/or verify. While you can't avoid this in the
case of objects that are meant stick around for a while, these objects
will only last for the duration of the SomeMethod call. (B) If you (or
someone else) later call SomeMethod somewhere else, you may be nastily
surprised to find that it Free's Self and it's parameter ....
Quote
> Which brings up another question: Does a variable declaration of a class
> automatically call that class's constructor, like in C++?
No.
--
Personal Pages http://www.midnightbeach.com/jon
Programming Publications http://www.midnightbeach.com/jon/pubs
Homeschool Resource Page http://www.midnightbeach.com/hs