Copy constructors for lazy initialization

Jonathan M Davis jmdavisProg at gmail.com
Sat May 29 02:32:53 PDT 2010


Actually, I have to ask what the purpose behind this delayed initialization 
is in the first place. The following works just fine as things are:

    int[] a;

    assert(!a);

    a ~= 42;

    assert(a);


If a were an object, this wouldn't work at all - even if it implemented the 
concatenation assignment operator. It would be null until you actually 
assigned it an object. Arrays - both normal and associative - don't seem to 
operate this way at all. This has the advantage that it's a bit hard to get 
the program to blow up on a null array, but it's not like that would 
generally be hard to find and fix. It makes it bit hard to have actual null 
array which stays that way. It would be easy to make an array null and 
accidentally add something to it, resulting in a bug which would have been 
found if the array didn't create itself upon concatenation. Also, you get 
the problem which started this thread - that of it getting created in a 
function that it's passed to and not ending up in the function that did the 
passing.

Other than having to update existing code, it doesn't seem that onerous to 
me to require

int[] = new int[](0);

to have an empty array if you want one (though it is a little weird to 
create an array of length 0).

Are there bugs that I'm not thinking of which the current behavior of 
creating the array for you avoids? Or am I just missing something here? It 
really seems to me like you're creating a workaround for a problem in the 
language. And while that workaround may be great for other stuff too, just 
making arrays stay null until the programmer assigns them another value 
fixes the bug that you're trying to fix - at least as far as I can tell. I 
don't understand why the current behavior was chosen. It does simplify array 
creation somewhat, but it seems to me that it's more likely to cause bugs 
than avoid them.

- Jonathan M Davis


More information about the Digitalmars-d mailing list