Copy constructors for lazy initialization
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Thu Jun 3 06:48:34 PDT 2010
On 06/03/2010 06:30 AM, Bruno Medeiros wrote:
> On 29/05/2010 03:02, Jonathan M Davis wrote:
>> Andrei Alexandrescu wrote:
>>
>> 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
>
> Yeah, I agree. I mean, for me the problem here is that the
> map/associative-array is not really a value type, nor a reference type,
> but something in between. I think it might be better for it to be just a
> proper reference type.
An associative array is a reference type. The problem discussed above
applies to all reference types.
> I'm not saying that Andrei suggestion has no merit though. Rather, I
> have to admit I am not familiar with these C++ idioms and techniques.
> Can someone explain me why we need a copy constructor in the first
> place, instead of just using a reference object, aka a class, and an
> optional clone method?
The problem is that null objects don't obey reference semantics. The
example discussed in this group is:
void fun(int[int] a) { a[5] = 10; }
void main(string[] args) {
int[int] x;
if (args.length & 1) x[0] = 42;
fun(x);
assert(x[5] == 10);
}
The program will fail or not depending on the number of arguments passed.
Andrei
More information about the Digitalmars-d
mailing list