Hi all !
Hi all !
I can't find an answer to the following question :
Is there an interest to use var in an object declaration as parameter :
Procedure GetResults(pID : Integer ; var pResults : TList);
vs
Procedure GetResults(pID : Integer ; pResults : TList);
as objects are passed by ref anyway ? and does const has a meaning in object declarations ?
I can't find an answer to the following question :
Is there an interest to use var in an object declaration as parameter :
Procedure GetResults(pID : Integer ; var pResults : TList
vs
Procedure GetResults(pID : Integer ; pResults : TList
as objects are passed by ref anyway ? and does const has a meaning in object declarations ?
if you had const pResults:... then you can only call methods on pResults, not assign to it(i.e. pResults := TList.Create).
ReplyDeleteIn your case, using or not using var shouldn't be any difference since it's a pointer behind the scenes.
OK, so IIUC then putting const in all objects declaration as parameter is a
ReplyDeletegood practice, as assigning a parameter object inside a function is not
recommended ?
usually it is, because the compiler can do much more aggresive optimisations when it knows that the caller won't be able to do nasty stuff.
ReplyDeleteas for assigning an instance to a parameter... this is very debatable at religious scale depending on who you ask, personally, I go for what works for me, but usually, it's a good practice to create and free objects in the same method if possible.
const can be funny:
ReplyDeleteUsing const for managed arguments is ok.
Using const for Objects is ok (at least pre ARC)
Using const for Interfaces can be tricky.
Example:
procedure DoSomething(const AIntf: IInterface);
begin
if Assigned(AIntf) then;
end;
If you just pass a variable to DoSomething, everything is fine. If you do something like this: DoSomething(TInterfacedObject.Create()) you are facing a memleak.
Post ARC it should be the same for Objects.
Olivier SCHWAB Use var for an object parameter when the method actually create an object and has to return that object reference.
ReplyDelete