> First, I'm confused now about freeing memory and also about understanding 
> what's passed, memory-wise, by parameters in methods ("x:TSomething" vs. 
> "var x:TSomething" vs "const x:TSomething") ...
>   
X:TSomething is a instance of the class TSomething. When you instanciate 
an object of the class TSomething (calling it's Create constructor) you 
actually get a pointer to a dynamically allocated area of memory that 
store's all of TSomething's fields (plus the fields of all it's parents, 
plus some very important things like the VM table). So "X" is in fact an 
pointer, a 4 byte indicator of where the stuff that goes into TSomething 
actually is (note: pointers are 4 bytes long on 32 bit machines). That 
being sad, when you call a procedure taking a parameter of type 
"X:TSomething" you're actually passing an pointer to the memory area, 
not the actual content of TSomething. I'm not sure about the "const" 
case. AFAIK there is no difference betwen calling a procedure taking 
"X:TSomething" as a parameter and calling a procedure taking "const 
X:TSomething" as a parameter. The difference is in the CALLED procedure: 
You can't change a "const" parameter so the meaning of that parameter is 
guaranteed to be consistent in the whole of the procedure. Please note: 
While you cant change the actual "X" in a "const X" procedure, you can 
change any of the fields of the object that X points to!

Ex:

procedure p1(X:TSomething);
begin
  X.DoSomenthing;
  X := TSomethin.Create;
  X.Free;
end;

procedure p2(const X:TSomething);
begin
  X := TSomething.Create; // Error! You can't do that
  X.Something := 1; // OK
  X.Free; // OK!
end;

When you pass "X" as a var parameter you're actually passing a pointer 
to a pointer to the allocated memory area for TSomething. This is 
usefull when you want the CALLED procedure to be able to change the 
value of X in the CALLING procedure. Ex:

procedure called_proc(var X:TSomething);
begin
  X := TSomething.Create;
end;

procedure calling_proc;
var aVar:TSomething;
begin
  called_proc(aVar); // This will initialize aVar with a new object!
  aVar.Free;
end;

This is the story with the "var X" parameter. I see no practical use for 
it...
_______________________________________________
Delphi mailing list -> Delphi@elists.org
http://www.elists.org/mailman/listinfo/delphi

Reply via email to