On 14/7/20 8:13, Kagamin wrote:
---
import std;

shared class TimeCount {
     void startClock() {
         auto me = cast()this;
         me.startTime = Clock.currTime;
     }
     void endClock() {
         auto me = cast()this;
         me.endTime = Clock.currTime;
     }
     void calculateDuration() {
         auto me = cast()this;
         me.elapsed = me.endTime - me.startTime;
     }

     private:
     SysTime startTime;
     SysTime endTime;
     Duration elapsed;
}
---
And this is shorter than your unshared member specification.

It won't work if you need to do it inside a struct instead of a class, because you'll get a copy:

```
import std;

shared struct S {
    void setA (int _a) {
        auto me = cast() this;
        me.a = _a;
    }
    int a;
}

void main() {
    shared S s;
    writeln("Before: ", s.a); // 0
    s.setA(42);
    writeln("After: ", s.a); // still 0
}
```

That said, `with (cast() this) { ... }` *will* work, because there's no copying. This is a really nice idiom that I didn't know and that I'll use from now on.

*However*, for this to work, you shouldn't use `shared` member variables unless absolutely necessary, much less whole `shared` classes/structs, and only declare the individual methods as shared, because casting away `shared` from `this` will only peel the external layer:

```
import std;

struct S {
    SysTime a;
    shared SysTime b;

    synchronized shared void setIt(SysTime t) {
        with(cast() this) {
            a = t;
// b = t; // FAILS, `b` is still `shared` even for non-shared `S`
        }
    }
}
```

Also, I'm pretty sure there are still corner cases when you have to nest data structures, but so far this strategy seems good enough.
            • Re:... Jonathan M Davis via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Steven Schveighoffer via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Steven Schveighoffer via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Kagamin via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Kagamin via Digitalmars-d-learn
            • Re:... Kagamin via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Dominikus Dittes Scherkl via Digitalmars-d-learn
            • Re:... Arafel via Digitalmars-d-learn
            • Re:... Kagamin via Digitalmars-d-learn
        • Re: how to a... Kagamin via Digitalmars-d-learn
          • Re: how ... Steven Schveighoffer via Digitalmars-d-learn
  • Re: how to assign to shar... Jonathan M Davis via Digitalmars-d-learn

Reply via email to