Copy constructors for lazy initialization

Michael Rynn michaelrynn at optusnet.com.au
Sat May 29 18:21:49 PDT 2010


On Fri, 28 May 2010 20:26:50 -0500, Andrei Alexandrescu wrote:

> 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
> 
> this(this);
> 
> 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;
>     foo(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?
> 
> 
> Andrei

Nothing wrong with yet another widely available constructor tool if the 
user optionally wants to have it available and use it that way, and its 
usage is well defined.

Good if no cost if the programmer does not use the facility.

What seems to be missing, in this example of the unintentional creation 
of 2 AAs because initially a null AA is passed, if there was a way of 
explicitly initialising the AA first without having to insert something 
into it.   That subject seems to be taboo.  Of course, an empty but setup 
AA can be kludged by adding an arbitrary value and then removing it, and 
as such begs the need for a setup property / function.

\\




More information about the Digitalmars-d mailing list