[Issue 11343] [2.064 beta] Error: multiple field initialization

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Oct 25 00:52:01 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=11343



--- Comment #5 from Kenji Hara <k.hara.pg at gmail.com> 2013-10-25 00:52:00 PDT ---
(In reply to comment #4)
> After my imagination, a constant member can be assigned as many times as I
> want, as long as it happens in the constructor. This is only logical.
> Everything else just makes it complex and completely non intuitive, especially
> for newbies.

A const reference may refer immutable data which comes from the out of the
constructor. If so, modifying const data inside constructor is definitely
illegal operation. By disallowing multiple initialization, compiler can
validate the field initializing correctness or not, at the first initializing
place.

====

Additionally, it is necessary to make immutable field data initialization more
flexible.
Today, if a pure function returns mutable data, it could be implicitly
convertible to immutable data.

    int[] make(int n) pure {
        int[] a = new int[](n);
        foreach (i; 0 .. n)
            a[i] = i + 1;
        return a;   // [1, 2, ..., n]
    }
    immutable int[] arr = make(n);  // OK

>From 2.064, by fixing issue 9665, compiler can detect the only once
initializing point for the object fields. 
Combine pure function, you can initialize immutable data field as follows.

struct S
{
    immutable int[] arr;

    this(int n)
    {
        static int[] make(int n) pure {
            int[] a = new int[](n);
            foreach (i; 0 .. n)
                a[i] = i + 1;
            return a;   // [1, 2, ..., n]
        }
        arr = make(n);
        // This line is now initialization (not assignment), so
        // conversion from mutable to immutable is allowed
    }
}
void main()
{
    auto s = S(10);
    assert(s.arr[0] == 0);
    assert(s.arr[$-1] == 10);
    static assert(is(typeof(s.arr) == immutable int[]));
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list