On Tuesday, 5 August 2014 at 20:32:08 UTC, Philippe Sigaud wrote:
But the compiler tells me 'need this for i of type int[]'.
Is there any way I can gain access on i inside B?


Been thinking about this a bit. I know some of my relies are in the 2012 fourm posts regarding it, but access permissions seems like the biggest reason, or rather lack of control of them.

 So take your example:

struct A
{
    int[] i;
    B b;
}

Now let's make a couple instances of it; And assume it would work...

 A a;
 immutable A i_a;

 a.b.foo(); //fine
 i_a.b.foo(); //won't run, due to not being const/immutable

So, a user decides let's copy the inner struct. If the struct copies it's attached secondary pointer going to it's outer/host, then:

 A.B b = a.b;
 A.B i_b = i_a.b;
 A.B broken_b = cast(A.B) i_a.b;

 b.foo(); //attached to a still, works...
 i_b.foo(); //const or immutable, won't work.
broken_b.foo(); //i_a is accessible invisibly because overridden or transformed assuming it would be converted or copied/moved as appropriate.

return b; //if a is a local variable then b becomes invalid even though it's a struct.
 return i_b; //same as return b
 return broken_b; //same as above two cases.




inner structs in a function where the struct is never passed outside the function would probably work though...

void func() {
  int[] i;
  struct B {
    void foo() { i ~= 1;}
  }

  B b;

b.foo(); //passed a reference to the current frame along with it's local 'this', but since it never leaves the function it's safe.
}




Now a current way to make it safe while still leaving it structs could be passing a reference to either the outer struct or the variable in question. For simplicity it would probably be the struct.

struct A
{
    int[] i;
    B b;

    struct B
    {
        void foo(ref A outer) { outer.i ~= 1;}
    }

    void bar() //call B foo
    {
        b.foo(this);
    }
}

Or less safe is to use a pointer and assign it when b instantiates to point back to A.. But if you pass B around without A and A goes out of scope... same problem...

 Maybe i'm over-thinking it.

Reply via email to