On Tuesday, 25 June 2024 at 02:25:14 UTC, Richard (Rikki) Andrew Cattermole wrote:
On 25/06/2024 2:16 PM, mw wrote:
struct shared_AA {
  shared_AA_class saa = new shared_AA_class();  // by this syntax `saa` is still instance variable?
   alias saa this;
}

When you specify an initializer like this, that instance of ``shared_AA_class`` gets put into the .init of ``shared_AA``.


This is confusing -- well, let's try something similar in C++ and Java:

```
$ cat shared_aa.cpp
#include <stdio.h>

class shared_AA_class {
public:
  int aa;
  shared_AA_class() {
          printf("new shared_AA_class\n");
  }

  void print() {
          printf("%d\n", aa);
  }
};

struct shared_AA {
shared_AA_class* saa = new shared_AA_class(); // by this syntax `saa` is still instance variable
};

class Foo {
public:
 shared_AA x;
 shared_AA y;

 Foo() {
    x.saa->aa = 1;  // only modified `x`, not `y`
 }

};

int main() {

        Foo foo;

        foo.x.saa->print();
        foo.y.saa->print();

        printf("%d\n", foo.x.saa->aa);
        printf("%d\n", foo.y.saa->aa);
}

$ g++ shared_aa.cpp
$ ./a.out
new shared_AA_class
new shared_AA_class
1
0
1
0
```

The `shared_AA_class` ctor is called twice, and `foo.x.saa` and `foo.y.saa` are different object.


```
$ cat Foo.java
class shared_AA_class {
 public
  int aa;
  shared_AA_class() {
          System.out.println("new shared_AA_class");
  }

  void print() {
          System.out.println(aa);
  }
}

class shared_AA {
shared_AA_class saa = new shared_AA_class(); // by this syntax `saa` is still instance variable
}

class Foo {
         shared_AA x;
         shared_AA y;

        Foo() {
    x = new shared_AA();
    y = new shared_AA();
                x.saa.aa = 1;  // only modified `x`, not `y`
        }

public static void main(String[] args) {

        Foo foo = new Foo();

        foo.x.saa.print();
        foo.y.saa.print();

        System.out.println(foo.x.saa.aa);
        System.out.println(foo.y.saa.aa);
}

}

$ javac Foo.java
$ java Foo
new shared_AA_class
new shared_AA_class
1
0
1
0


```

The `shared_AA_class` ctor is called twice, and `foo.x.saa` and `foo.y.saa` are different object.


Why D choose to be different here? i.e. `shared_AA_class saa = new shared_AA_class()` only evaluate only once, and even force it must be evaluate-able at compile time?


  • Why `foo.x.saa.a... mw via Digitalmars-d-learn
    • Re: Why `fo... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
      • Re: Why... mw via Digitalmars-d-learn
        • Re:... Kagamin via Digitalmars-d-learn
        • Re:... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
    • Re: Why `fo... Nick Treleaven via Digitalmars-d-learn

Reply via email to