Compiler error with slices, .dup and ref Parameter

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 20 05:55:20 PST 2014


On 11/20/14 7:28 AM, anonymous wrote:
> On Thursday, 20 November 2014 at 09:20:34 UTC, Ali Çehreli wrote:
>> Judging from the name init(), I don't think you need ref anyway.
>
> thanks for the explanation. I can't remove the ref because it is
> Main.init in gtkd.
> A simple solution is init(args)
> I just tried to remove a non-GTK argument (a filename) via slicing. This
> is not necessary at all...

To further explain:

The only reason you would need to pass a string[] by ref is if you 
wanted to modify the order/size of the array. A string[]'s data is 
already passed by reference, so there is no need to ref it otherwise.

What I am guessing gtkd does, is that it processes GTK-specific 
parameters from the argument string array, then *removes* those from the 
arguments.

If you did *not* pass by reference, these modifications would be corrupt 
when you looked at the original.

This is best illustrated by an example:

void foo()(auto ref string[] x)
{
     // remove all blanks
     size_t i, j;
     for(i = 0, j = 0; i < x.length; ++i)
     {
         if(x[i].length)
             x[j++] = x[i];
     }
     x.length = j;
}

void main()
{
     auto arr = ["a", "b", null, "c", "d"];
     foo(arr[0..$]); // pass by value
     assert(arr == ["a", "b", "c", "d", "d"]); // oops, extra "d"
     arr = ["a", "b", null, "c", "d"];
     foo(arr); // now by reference
     assert(arr == ["a", "b", "c", "d"]);
}

So the compiler is saving you from a mistake :)

-Steve


More information about the Digitalmars-d-learn mailing list