开发者

Delphi: Pass by reference or pass by value?

In Delphi, 开发者_开发百科if I have a simple class myClass and I pass an instance of it to a function with myFunction( myClass ), which is defined by function myFunction( myObject : myClass ) : Boolean...

  • Will a copy of myObject be made?

  • When I call methods of myObject in myFunction, will the original object be affected and modified too?


Objects are passed by reference. A copy will not be made; there will be only one instance of the class, only one object. The original object is all there is.


In Delphi, objects are special pointers which refer to a data structure on heap memory. When you pass an object to a function, you are actually passing the pointer, not a copy of the whole object data. In this case, when you modify a field or property via that reference, it will affect the original object data. Here is a simple example demonstrating this behavior:

program ObjParamTest;

type
  TMyClass = class
  private
    FMyField : Integer;
  public
    property MyField : Integer read FMyField write FMyField;
  end;


function ModifyObject(AnObj: TMyClass);
begin
  AnObj.MyField := AnObj.MyField + 1;
end;  

var
  MyObj : TMyClass;
begin
  MyObj := TMyClass.Create;
  try
    AnObj.MyField := 2;
    Writeln(AnObj.MyField); // ==> Prints 2
    ModifyObject(MyObj);
    Writeln(AnObj.MyField); // ==> Prints 3
  finally
    MyObj.Free;
  end;
end.

Also take note, parameter modifiers (e.g. Var, Const, Out) only change the way the object reference is passed to the function, and have no effect on the original data structure.

Maybe this article clears up things about different ways of passing parameters to functions in Delphi for you more:

Different function parameter modifiers in Delphi (archived version)


There's a bit more to it than "objects are passed by reference." Objects are reference types, and so they're always passed around by reference by default. Any object variable is an object reference.

But if you pass an object variable "by reference," (to a var parameter,) then if you replace the object with a different object inside the routine you passed it to, you'll end up with a different object once the routine returns. Be careful when doing this; it can cause memory leaks if you change the only reference you have to a certain object.


The objects are passed by reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜