Delphi passing parameters by reference or by value/copy

Vitim.us picture Vitim.us · Mar 3, 2012 · Viewed 30.6k times · Source

Context 1

var text:String;

text:='hello';

myFunc(text);

Context2

function myFunc(mytext:String);
var textcopy:String;
begin

    textcopy:=mytext;

end;

myFunc on the Context2 was called from the Context1, the local variable mytext is pointing to a memory outside the Context2? or the mytext have have their own memory space inside the scope, and filled/copied with the same content of the text? I'm probably missing something really basic, because I'm getting a access violation error.

There's any way to specify explicitly if a function should receive parameters by reference or by value, copying then like in C? I'm not sure about how I'm doing it.

Answer

Nick Barnes picture Nick Barnes · Mar 3, 2012

Memory management for Delphi strings is a little unusual. After you call myFunc(text), and assign textcopy := mytext, all three variables (text, mytext and textcopy) will be pointing to the same address, that of the original string.

But as soon as you use one of these variables to make changes to the string, Delphi clones the string behind the scenes, and your changes are applied to the copy. The other two variables still point to the original, so they remain unchanged. So any changes made in Context 2 will not be seen in Context 1 - this "copy-on-write" mechanic effectively gives you pass-by-value semantics. All of these strings are reference-counted, and will be freed automatically once all references go out of scope.

However, there is an exception. If you access the string using pointers, rather than string operations, you'll bypass the copying step and your changes will affect the original. You'll also bypass the reference counting logic, and potentially end up with a pointer to a deallocated block of memory. This may be the reason behind your access violation, but I couldn't say without more details / more code.

If you want reference passing, declare your function as myFunc(var mytext: String). If you want to force Delphi to copy the string, instead of waiting until it's modified, you can use System.UniqueString.