static __gshared struct

Hiemlick Hiemlicker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 1 17:08:10 PDT 2016


On Friday, 1 July 2016 at 23:36:35 UTC, Basile B. wrote:
> On Friday, 1 July 2016 at 23:26:19 UTC, Hiemlick Hiemlicker 
> wrote:
>> On Friday, 1 July 2016 at 23:03:17 UTC, Basile B. wrote:
>>> On Friday, 1 July 2016 at 22:47:21 UTC, Hiemlick Hiemlicker 
>>> wrote:
>> Ok, Does that mean
>>
>>
>>> void main()
>>> {
>>>     static struct Foo{}
>>       foo();
>>> }
>>
>> void foo()
>> {
>>    Foo f;
>> }
>>
>> works?
>
> No.
>
> An example usage is for the singleton pattern:
>
>     T singletonViaFactory(T, A...)(A a)
>     if (is(T == class))
>     {
>         static T instance;
>         if (instance)
>             return instance;
>         else
>             return new T(a);
>     }
>
> "instance" is well a global variable and not a local, but it's 
> hidden from the outside world.
>
>> Also, then how do I declare a struct to be "global" so that it 
>> can be common to all threads? Do I have to declare _gshared 
>> for each element of the struct?
>
> no, just put __gshared before the variable declaration, not for 
> each member:
>
>     struct Foo
>     {
>         int i;
>     }
>
>     __gshared Foo foo;
>
> is fine.

I use a struct with static members so I do not have to 
instantiate it. It is essentially a singleton. I want all the 
variables to be __gshared. I guess I have to prefix all variables 
with it?

Basically I have Foo.i; on foo. i is static, of course. I also 
want it to be __gshared.

Makes sense to me that

__gshared struct x;

all of x's variables should be __gshared.





More information about the Digitalmars-d-learn mailing list