Copy constructors for lazy initialization

Steven Schveighoffer schveiguy at yahoo.com
Fri May 28 21:33:25 PDT 2010


On Fri, 28 May 2010 21:26:50 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

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

I'm almost positive you meant "allow *structs* to define"

>
> this(ref S src);
>
> where S is the name of the struct being defined, as an alternative for
>
> this(this);
>

[snip]

> 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?

It is a good effort to solve the problem.  The problem I see with such  
constructs is inherently the lazy construction.  Because you must lazily  
construct such a container, every method meant to be called on the struct  
must first check and initialize the container if not done already.  This  
results in an undue burden on the struct author to make sure he covers  
every method.  The first method he forgets to lazily initialize the struct  
results in an obscure bug.

I wonder, would it be possible to go even further?  For example, something  
like this:

struct S
{
   lazy this()
   {
      // create state
   }
}

which would be called if the struct still has not been initialized?  lazy  
this() should be prepared to accept an already initialized struct, which  
should be no problem because most lazily initialized structs always differ  
 from the .init value.

The compiler could optimize this call out when it can statically determine  
that a struct has already been initialized.

This of course, does not cover copy construction, but it would be called  
before the copy constructor.

BTW, I'm glad you guys are looking at this problem.

-Steve


More information about the Digitalmars-d mailing list