On 4/15/23 09:06, NonNull wrote:

>> struct Wrapper
>> {
>>    Object x = new Object();
>>    alias x this;
>> }

> Amazing, was this always so?

At least for a long time. However, every Wrapper object will have a pointer to that single shared object.

If you think that cost is unnecessary, you can have a static variable:

struct Wrapper
{
   static Object x;
   alias x this;
}

static this() {
    Wrapper.x = new Object();
}

However, because such data are thread-local by-default, not the entire class, but each thread will have a copy that variable.

When you want a single class variable for all threads, then it must be defined as shared:

struct Wrapper
{
   shared static Object x;
   alias x this;
}

shared static this() {
    Wrapper.x = new Object();
}

void foo(shared Object o)
{
   assert(o !is null);
}

Note how foo's interface had to be changed as well. And of course you may have to provide thread synchronization when that variable needs to be mutated at run time.

Ali

Reply via email to