New feature proposal: "initialization scope"

Jonathan M Davis jmdavisProg at gmx.com
Thu May 16 01:31:11 PDT 2013


On Thursday, May 16, 2013 10:20:16 TommiT wrote:
> On Thursday, 16 May 2013 at 08:01:33 UTC, deadalnix wrote:
> > This is easy to work around that using a mutable data,
> > construct it and then copy it to a const one.
> > 
> > You my argue that this is slower, and I answer you : maybe. Can
> > you show what does GDC or LDC output doing so ?
> 
> I could also argue that it's just not very elegant solution.
> You're left with this extra, useless dummy variable (the initial,
> mutable one) that you're not supposed to use.
> 
> Also, I'd like to initialize immutable variables plus there's the
> possible performance issue (don't have time to do a test now).

Well, that's the standard way to do it. If you can't initialize a const or 
immutable variable in one go, you create a mutable one and then cast it (or 
use assumeUnique) on it and assign it to the const/immutable variable that you 
wanted to initialize. For module-level and static variables, you'd generally 
do it in a static constructor, though that isn't an option for local 
variables. In their case though, if you don't want two variables floating 
around, you can always use a nested function (or some other function) to 
generate the mutable variable and then return it as const or immutable.

Normally, there's no performance hit to doing any of this, but it is true that 
that's a potential issue in your example, because it's a static variable. I 
question that that merits adding a new feature to the language though. The 
trick of creating it as mutable and then casting it to immutable works quite 
well overall and really hasn't been causing problems.

- Jonathan M Davis


More information about the Digitalmars-d mailing list