on structs by reference
Alex via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 16 05:09:09 PST 2015
On Monday, 16 November 2015 at 07:51:53 UTC, Ali Çehreli wrote:
>
> 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]
>
Ok, this definitely helps. Thank you!
For me, the key point here is, that my struct S, which use one of
the slices in the Slice of slices does not own it. This is ok.
So, I have to think about who owns the Slice of slices now,
because only this 'something' should be able to rearrange its
data...
The cool thing is, that it will be able to modify the data
THROUGH the s structs, as in the line
s.arr ~= 4;
and is not restricted to. So, new S structs are generated by
operating on the Slice of slices directly and old slices can be
modified by operating on the appropriate S struct.
Thanks again for helping zooming out...
More information about the Digitalmars-d-learn
mailing list