digitalmars.D.learn - Static struct?
- JN (8/8) Apr 24 2019 I noticed a construct I haven't seen before in D when reading the
- Rubn (20/29) Apr 24 2019 You can access variables in the current scope when in a nested
- user1234 (17/26) Apr 24 2019 It's like if it's declared at the global scope, meaning that it
- H. S. Teoh (13/24) Apr 24 2019 In module-global scope, nothing.
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?
Apr 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 ); }
Apr 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 }
Apr 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.
Apr 24 2019