Thread overview
Static struct?
Apr 24, 2019
JN
Apr 24, 2019
Rubn
Apr 24, 2019
user1234
Apr 24, 2019
H. S. Teoh
April 24, 2019
I noticed a construct I haven't seen before in D when reading the description for automem - https://github.com/atilaneves/automem

 static struct Point {
        int x;
        int y;
    }


What does "static" do in this case? How does it different to a normal struct?
April 24, 2019
On Wednesday, 24 April 2019 at 21:12:10 UTC, JN wrote:
> I noticed a construct I haven't seen before in D when reading the description for automem - https://github.com/atilaneves/automem
>
>  static struct Point {
>         int x;
>         int y;
>     }
>
>
> What does "static" do in this case? How does it different to a normal struct?

You can access variables in the current scope when in a nested scope, static prevents this so that you don't accidentally access any of those values as it adds overhead to the struct.

https://run.dlang.io/is/QNumbz

void main() {
    import std.stdio;

    int x;
    struct A {
         void test() { x = 10; }
    }

    static struct B {
        // void test() { x = 20; } // Error
    }

    A a;
    B b;

    a.test();
    // b.test();

    writeln( x );
}
April 24, 2019
On Wednesday, 24 April 2019 at 21:12:10 UTC, JN wrote:
> I noticed a construct I haven't seen before in D when reading the description for automem - https://github.com/atilaneves/automem
>
>  static struct Point {
>         int x;
>         int y;
>     }
>
>
> What does "static" do in this case? How does it different to a normal struct?

It's like if it's declared at the global scope, meaning that it doesn't know the context and cant access, if declared in a function, the stack frame. Now dependeding on the location, static can be a noop.

module foo;

static struct One {} // noop

void bar()
{
    int i;
    static struct Two { void stuff(){ i = 42:} } // error
}

void baz()
{
    int i;
    struct Three { void stuff(){ i = 42:} } // ok
}


April 24, 2019
On Wed, Apr 24, 2019 at 09:12:10PM +0000, JN via Digitalmars-d-learn wrote:
> I noticed a construct I haven't seen before in D when reading the description for automem - https://github.com/atilaneves/automem
> 
>  static struct Point {
>         int x;
>         int y;
>     }
> 
> 
> What does "static" do in this case? How does it different to a normal struct?

In module-global scope, nothing.

In function/aggregate scope, means the struct won't have the hidden context pointer to its lexical container, so you won't be able to access variables from the containing scope.  OTOH, it also makes it possible to instantiate the struct outside that scope (since otherwise it's not possible to construct it with the proper context pointer).

So ironically, 'static' in this case actually means "normal", as opposed to a struct that carries a hidden context pointer and has restrictions as to where/how it can be used.


T

-- 
Frank disagreement binds closer than feigned agreement.