Simple immutable example doesn't work - why???

TheFlyingFiddle theflyingfiddle at gmail.com
Mon Nov 11 17:33:27 PST 2013


On Tuesday, 12 November 2013 at 01:15:02 UTC, Louis Berube wrote:
> I thought the parantheses in the array declaration would do the 
> trick, but apparently not.

Well when you create an immutable array you cannot change any of 
the elements in the array. I'm guessing what you want is a 
mutable array that contains immutable objects. I don't think you 
can create such an array in D (i am not sure though i doubt that 
it would be usefull anyhow)

However if you want to build a mutable array and then make the 
entire structure immutable do something like this.

class Test
{
    private uint value;

    //Ctor needs to be immutable to create immutable objects.
    this(uint value) immutable
    {
       this.value = value;
    }

    //We need this to be able to construct initially mutable 
objects.
    this(uint value)
    {
       this.value = value;
    }
}

unittest
{
   auto array = buildTests(5);
}

immutable(Test)[] buildTests(uint num)
{
    import std.exception : assumeUnique;
    auto array = new Test[num];
    foreach(i; 0 .. num) {
       array[i] = new Test(i);
    }

    //Since we hold the only value that can be mutated
    //here its ok to assume that this array is immutable.
    //also making it immutable will make all the elements
    //immutable.
    return assumeUnique(array);
}


More information about the Digitalmars-d-learn mailing list