Static member inside a class.

Agustin agustin.l.alvarez at hotmail.com
Thu Jun 13 13:09:12 PDT 2013


On Thursday, 13 June 2013 at 19:59:11 UTC, Steven Schveighoffer 
wrote:
> On Thu, 13 Jun 2013 15:47:22 -0400, Agustin 
> <agustin.l.alvarez at hotmail.com> wrote:
>
>> I would like to know if static members are shared between 2 
>> library. For example:
>>
>> Class A
>> {
>>  static uint var;
>> }
>>
>> From Library A:
>>
>> A::var = 3;
>>
>> From Library B:
>>
>> if( A::var == 3 )
>>   ...
>>
>> Its this possible? if not, its any way to make it happend?
>
> It's possible, and works just like you have it (syntax is 
> slightly different, use A.var)
>
> However, static means "thread local"  So you can't access the 
> same A.var from multiple threads.
>
> To access from multiple threads, declare var like:
>
> shared static uint var;
>
> -Steve

On Thursday, 13 June 2013 at 20:00:59 UTC, w0rp wrote:
> On Thursday, 13 June 2013 at 19:47:23 UTC, Agustin wrote:
>> I would like to know if static members are shared between 2 
>> library. For example:
>>
>> Class A
>> {
>> static uint var;
>> }
>>
>> From Library A:
>>
>> A::var = 3;
>>
>> From Library B:
>>
>> if( A::var == 3 )
>>  ...
>>
>> Its this possible? if not, its any way to make it happend?
>
> The members are shared between different modules, yes. You use 
> . instead of :: for scope resolution. You can also initialise a 
> few things in a static constructors at class scope...
>
> class A {
>     static uint var;
>
>     static this() {
>         var = 3;
>     }
> }
>
> Or at module scope...
>
> class A {
>     static uint var;
> }
>
> static this() {
>     A.var = 3;
> }
>
> You should note that the data isn't shared between threads by 
> default, but that's another detail. You can also usually 
> produce a design that uses non-static data instead of static 
> data.

Thanks for taking the time to explain me, i'm currently doing an 
event system for my game, and i came out with the idea of an 
Event System.

\ [1] - Map each event to an ID with their name.

Event
{
  .....
}

PlayerLoginEvent : Event
{
  .....
}

EventManager.callEvent(PlayerLoginEvent(Player));
EventManager.registerListener!PlayerLoginEvent(delegate)
{
   Map[ID(PlayerLoginEvent.Name)] ~ delegate;
}

\ [2] - Have a static list inside each event class.

PlayerLoginEvent : Event
{
   Static Delegates;

   ....
}

EventManager.registerListener!PlayerLoginEvent(delegate)
{
   // T -> Template
   T.Delegates ~ delegate; // No lookup in a associative array.
}

So thats why i was asking about the static member, thanks!.


More information about the Digitalmars-d-learn mailing list