Arrays passed by almost reference?
Travis Boucher
boucher.travis at gmail.com
Thu Nov 5 12:44:02 PST 2009
Leandro Lucarella wrote:
> Andrei Alexandrescu, el 5 de noviembre a las 16:10 me escribiste:
>> Ali Cehreli wrote:
>>> Thanks for all the responses.
>>>
>>> And yes, I know that 'ref' is what works for me here. I am trying to figure out whether I should develop a guideline like "always pass arrays with 'ref', or you may face surprises."
>>>
>>> I understand it very well now and was able to figure out a way to cause some bugs. :)
>>>
>>> What can be said about the output of the following program? Will main.a[0] be printed as 1 or 111?
>>>
>>> import std.cstream;
>>>
>>> void modify(int[] a)
>>> {
>>> a[0] = 1;
>>>
>>> // ... more operations ...
>>>
>>> a[0] = 111;
>>> }
>>>
>>> void main()
>>> {
>>> int[] a;
>>> a ~= 0;
>>> modify(a);
>>>
>>> dout.writefln(a[0]);
>>> }
>>>
>>> It depends on the operations in between the two assignments to a[0] in 'modify':
>>>
>>> - if we leave the comment in place, main.a[0] is 111
>>>
>>> - if we replace the comment with this code
>>>
>>> foreach (i; 0 .. 10) {
>>> a ~= 2;
>>> }
>>>
>>> then main.a[0] is 1. In a sense, modify.a caused only "some" side effects in main.a. If we shorten the foreach, then main.a[0] is again 111. To me, this is at an unmanagable level. Unless we always pass with 'ref'.
>>>
>>> I don't think that this is easy to explain to a learner; and I think that is a good indicator that there is a problem with these semantics.
>> The ball is in your court to define better semantics.
>
> Just make arrays a reference value, like classes!
>
You mean dynamic arrays, but what about static arrays? Sometimes it
makes more sense to send a static array as a value rather then a
reference (think in the case of small vectors).
Then we'd have 2 semantics for arrays, one for static arrays and one for
dynamic arrays.
I am not fully against pass-by-ref arrays, I just think in passing by
reference all of the time could have some performance implications.
More information about the Digitalmars-d
mailing list