Separate dynamic object arrays for multiple instances of overlying object

An Pham home at home.com
Thu Mar 14 13:01:50 UTC 2024


On Thursday, 14 March 2024 at 10:21:41 UTC, Jonathan wrote:
>
> class Spectrum
> {
>     PrecursorList precursorList = new PrecursorList();
> }
>

> void main()
> {
>    SpectrumList mySpectrumList = new SpectrumList;
>    for(int j=0; j<mySpectrumList.count; ++j)
>    {
>    	    Spectrum mySpectrum = new Spectrum;
>         writeln(mySpectrum.precursorList.precursors.length); // 
> should always be 0
>         assert(mySpectrum.precursorList.precursors.length == 0);
>         for(int k=0; k<mySpectrum.precursorList.count; ++k)
>         {
>             Precursor myPrecursor = new Precursor;
>             mySpectrum.precursorList.precursors ~= myPrecursor;
>         }
>         mySpectrumList.spectra ~= mySpectrum;
>    }

> ```

You encounter a gotcha unfriendly construct of D. For every "new 
Spectrum", there is only one instant of mySpectrum.precursorList 
hence for subsequence iteration, the list is already filled with 
myPrecursor hence the assert problem. So either move that static 
new to constructor or in the loop

Cheers
Happy coding


More information about the Digitalmars-d mailing list