current "ref" args state.

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon May 19 03:16:12 PDT 2014


On Mon, 19 May 2014 09:34:48 +0000
evilrat via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> as topic says sometimes ref has a 'little' problem now, it is
> unavoidable in some cases and has some readability in code and
> much more...
>
> imagine we have a function "void getMyNumber(ref int number)"
> which assigns 42 to 'number', now lets look at C# code first:
>
> ----------- C# code -------------
> int someNumber = 3;
> MyCoolLibraryClass.getMyNumber(ref someNumber);
> ------------------------------
>
> ok, it clearly shows where our variable could be changed, now
> look at same D code:
>
> ----------- D code -------------
> int someNumber = 3;
> getMyNumber(someNumber);
> assert(someNumber == 42);
> ------------------------------
>
> wait... what? what does this function? is it using our nice
> variable to do some computation with it? or maybe it is assigned
> something to our varible? and what if we had lot of other
> function calls before this? how to know our variable stay the all
> time we feed it to functions?
>
> now this is the problem, ref arguments isn't that obvious as it
> should be, it is very easy to mess up in code and spent hours to
> see what's going wrong. currently i trying to add /*ref*/ comment
> before passing such variables to functions. we should really
> change this behaviout and add warning when passing ref args to
> functions if it doesnt have ref keyword like in C#, i don't ask
> to enfoce, but such little tweak would help a lot.
>
> i may overlooked proposals for this case, if any please give a
> link, sorry for possible duplicate topic.

It's been discussed before and shot down. Among other things, making ref at
the call site would break a lot of code, and it wouldn't play well with UFCS
at all. Also, making ref optional at the call site is by far worse than not
having it all, because then the lack of it still tells you absolutely nothing
but gives the false sense of security that it's not being passed by ref. And
we really shouldn't be adding more warnings, since in the grand scheme of
things, a warning is pretty much the same thing as an error, since not only
is it bad practice to leave warnings in your code, but the -w flag makes
warnings into errors anyway.

C++ is in the same situation with regards to its references, and it works
fine. However, folks do often use pointers instead of references in C++ in
order to make it clearer, and you're free to the same in D if you really don't
like having functions which have ref parameters.

I really don't expect that this aspect of D is going to change at this point.

- Jonathan M Davis


More information about the Digitalmars-d mailing list