Separate dynamic object arrays for multiple instances of overlying object

Mike Parker aldacron at gmail.com
Thu Mar 14 09:53:27 UTC 2024


On Thursday, 14 March 2024 at 09:43:09 UTC, Jonathan wrote:
> I'm having some trouble creating arrays that are themselves 
> unique within multiple instances of an object.  Example code:
>
>
> ```
> class individual
> {
>     int a = 1; // placeholder for data
> }
>
> class individualList
> {
>     individual[] individuals;  // Something likely has to 
> change here
> }
>
> void main()
> {
>     individualList list1 = new  individualList();
>     assert(list1.individuals.length == 0);
>     individual person1 = new individual();
>     list1.individuals ~= person1;
>     assert(list1.individuals.length == 1);
>
>     individualList list2 = new individualList();
>     assert(list2.individuals.length == 0); // breaks, 
> list2.individuals.length is 1
> }
> ```
>
>
> I'd like the array "individuals" to be unique for each instance 
> of individualList, but it seems to be using the same list among 
> the different instances.

Shouldn't be. Each non static class member is a distinct thing in 
each instance of the class. They are not shared across instances. 
When I paste your code into run.dlang.io and add this:

```D
     writeln(list1.individuals.length);
     writeln(list2.individuals.length);
```

No asserts trigger and I see this output as expected:

```
1
0
```

Is the code you pasted here exactly what you're running?


More information about the Digitalmars-d mailing list