Copy constructors for lazy initialization

Andrei Alexandrescu SeeWebsiteForEmail at
Fri May 28 18:26:50 PDT 2010

Walter has had a great idea last night: allow classes to define

this(ref S src);

where S is the name of the struct being defined, as an alternative for


The result would be a function similar with a C++ copy constructor.

Such an abstraction allows us to perform lazy initialization in a way 
that allows the kind of problems associated with non-shared hash tables:

void foo(int[int] x)
    x[5] = 5;

void main()
    int[int] x;
    assert(x[5] == 5); // fails

If you change the first line of main() with

int[int] x = [ 42:42 ];

the assert passes.

The idea of the copy constructor is to lazy initialize the source and 
the target if the source has null state. That would take care of this 
problem and the similar problems for shared state.

There is still a possibility to call a method against an object with 
null state. I think that's acceptable, particularly because lazy 
initialization saves some state allocation.

What do you think?


More information about the Digitalmars-d mailing list