[Issue 5603] Initialization syntax for dynamic arrays

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Feb 17 05:03:24 PST 2011


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



--- Comment #2 from bearophile_hugs at eml.cc 2011-02-17 05:00:47 PST ---
(In reply to comment #1)
> This does not need to be a language thing, library could suffice:

Of course, you may create template functions that do what I have shown (and
better).


> BTW, your code does not work properly for array appending.  It does not
> initialize the hidden "allocated length" field, which would likely result in
> reallocation on append.

I see, thank you. That code I have written is clearly bug-prone, that's why a
built-in syntax (or functions in Phobos) are useful.



> Some other functions probably needed:
> 
> a.extendUninit(size_t newlength);
> 
> which is like a.length = newlength but does not initialize the new area.

This is a possible thing to add. But it looks less useful because when you want
uninitialized memory, you want max performance, so you probably don't want to
change the array length.


> I agree a syntax change would be more in line with current array allocation
> operations (which are currently all syntax based), but I don't really like your
> proposed syntax.
> 
> I would propose if we wanted to do a syntax change to do:
> 
> auto a = new int[][](5, 5, 1);
> auto a = new int[][](5, 5, void);
> 
> Where the optional final argument determines the initial value.
> 
> This fits perfectly with the current array creation syntax:
> 
> new T(dim1, dim2, ..., dimN)
> 
> where T is a N dimensional array.  We can just add an extra parameter for the
> value.

I am strongly against this idea because it's too much bug-prone. It's too much
easy to add or remove a [] by mistake, or add or remove the initialization
value by mistake, so you may end with the wrong number of dimensions, etc.
auto a = new int[][](5, 5, 2);
auto a = new int[][][](5, 5, 2);
auto a = new int[][][](5, 5, 5, 2);



> One problem with this whole proposal is the issue with struct semantics.  That
> is, let's say a struct has a postblit, and you wanted to create an array of
> those structs with a default value.  Should the runtime call the postblit for
> each element?
> 
> I'd say it should.

This exactly same problem is present in the initialization syntax for
fixed-sized arrays, so the best solution is to just copy that semantics:

struct Foo {
    int x;
    this(this) {
        x++;
    }
}
void main() {
    Foo[2] foos = Foo(1);
    assert(foos[0].x == 2);
    assert(foos[1].x == 2);
}

-- 
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