Arrays passed by almost reference?

Leandro Lucarella llucax at gmail.com
Thu Nov 5 19:31:50 PST 2009


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!

-- 
Leandro Lucarella (AKA luca)                     http://llucax.com.ar/
----------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------
A lo que Peperino respondióles: aquel que tenga sabañones que se los
moje, aquel que padece calvicie no padece un osito, no es bueno comer
lechón en día de gastritis, no mezcleis el vino con la sandía, sacad la
basura después de las ocho, en caso de emergencia rompa el vidrio con
el martillo, a cien metros desvio por Pavón.
	-- Peperino Pómoro



More information about the Digitalmars-d mailing list