On 11/14/2015 07:53 AM, Alex wrote:

> 3. The only point I stumble on is, that the main feature in my program
> is, that the underlying array, to which my slices refer to never
> changes. So, I'm going to have more and more slices, which are going to
> be smaller and smaller and each points to the same underlying array
> without overlapping, but at each step, there are as much copies of a
> single slice as elements it points to. I hope this last point was not
> too weird.

Your struct objects must keep a reference to the slice that they use (i.e. one ore level of indirection).

Here is a start:

import std.stdio;

/* This is the storage to the slices that objects will share.
 *
 * (Surprisingly, creating a slice dynamically is not possible due
 * to syntax issues: new int[N] means "allocates N ints and make
 * a slice from those." However, we need a dynamic slice object
 * here. I've decided to put the slices in a 'slice slice' here.)
 */
int[][] slices;

struct S
{
    size_t idx;

    ref int[] arr()
    {
        return slices[idx];
    }
}

void main()
{
    S s; // = new S();
    slices ~= [1,2,3];
    s.idx = slices.length - 1;
    writeln(s.arr); //first

    S t; // = new S();
    t = s;
    writeln(t.arr); //second

    s.arr ~= 4;
    writeln(s.arr); //third
    writeln(t.arr);
}

[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4]

Ali

Reply via email to