Separate dynamic object arrays for multiple instances of overlying object

Jonathan daemon512 at gmail.com
Thu Mar 14 10:05:32 UTC 2024


On Thursday, 14 March 2024 at 09:53:27 UTC, Mike Parker wrote:
> 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?

You're right, my example code doesn't function as my nonworking 
code does, sorry about that.

No, this is not the same, the code that doesn't work is part of a 
1000+ line parser, I thought this example would work the same.  
I'm trying multiple loops to get the same problem, but I'm having 
trouble getting it to do so.  Will get back when I have a proper 
example.


More information about the Digitalmars-d mailing list