Mutable enums

Jonathan M Davis jmdavisProg at gmx.com
Sun Nov 13 16:09:40 PST 2011


On Sunday, November 13, 2011 19:02:01 bearophile wrote:
> Jonathan M Davis:
> > > import std.algorithm;
> > > void main() {
> > > 
> > >     enum a = [3, 1, 2];
> > >     enum s = sort(a);
> > >     assert(equal(a, [3, 1, 2]));
> > >     assert(equal(s, [1, 2, 3]));
> > > 
> > > }
> > 
> > It's not a bug. Those an manifest constants. They're copy-pasted into
> > whatever code you used them in. So,
> > 
> > enum a = [3, 1, 2];
> > enum s = sort(a);
> > 
> > is equivalent to
> > 
> > enum a = [3, 1, 2];
> > enum s = sort([3, 1, 2]);
> 
> You are right, there's no DMD bug here. Yet, it's a bit surprising to sort
> in-place a "constant". I have to stop thinking of them as constants. I
> don't like this design of enums...
> 
> On the other hand this gives the error message I was looking for, until
> today I didn't even think about const enums:
> 
> import std.algorithm;
> const enum a = [1, 2];
> void main() {
>     sort(a);
> }
> 
> 
> So I guess I'll start using "cont enum" and "immutable enum" instead of
> enums :-)

It depends entirely on what you're trying to do. If you understand how 
manifest constants work, then they can be quite advantageous. What you 
probably really want for arrays though is not an enum but just a const or 
immutable module variable.

immutable a = [3, 1, 2];

Otherwise, you're allocating a new array every time you use the enum. So, use 
a manifest constant when you want to avoid having it take up any memory but 
don't care about whatever allocations may occur when it's used (primitive 
types such as ints being a prime example), whereas if you want an actual 
memory location for the constant and/or want it to be allocated only once, 
then use variable rather than an enum.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list