Copy constructors for lazy initialization

Jonathan M Davis jmdavisProg at gmail.com
Fri May 28 19:02:01 PDT 2010


Andrei Alexandrescu wrote:

> What do you think?
> 
> 
> Andrei

Certainly, in the case provided, it's a definite win. I'm not sure what the 
overall implications would be though. Part of the problem stems from the 
fact that the array is initialized to null, and yet you can still add stuff 
to it. My first reaction (certainly without having messed around with it in 
D) would be that x[5] = 5 would fail because the array was null. However, 
instead of blowing up, D just makes the null array into an empty one and 
does the assignment. If D didn't allow the assignment without having first 
truly created an empty array rather than a null one, then we wouldn't have 
the problem.

Now, there may be very good reasons for the current behavior, and this 
suggestion would fix the problem as it stands. But it would still require 
the programmer to be aware of the issue and use this(ref S src) instead of 
this(this) if they were writing the constructor or be aware of which it was 
if they didn't write the constructor.

Not knowing what other implications there are, I'm fine with the change, but 
the fact that D creates the array when you try and insert into it (or append 
to it in the case of normal arrays IIRC) rather than blowing up on null 
seems like a source of subtle bugs and that perhaps it's not the best design 
choice. But maybe there was a good reason for that that I'm not aware of, so 
it could be that it really should stay as-is. It's just that it seems 
danger-prone and that the situation that you're trying to fix wouldn't be an 
issue if the array stayed null until the programmer made it otherwise.

- Jonathan M Davis


More information about the Digitalmars-d mailing list