Should all enums be immutable?

Don nospam at nospam.com
Mon Apr 4 02:32:47 PDT 2011


Jonathan M Davis wrote:
> Enum values cannot be altered. It is an error to try and assign a value to an 
> enum. However, the value of an enum isn't really const or immutable. It's 
> copied every time that the enum is used. This is fine in cases where the enum 
> is a value type, but it's problematic when the enum is a reference type. I 
> believe that the classic example is if you have an AA which is an enum. You 
> copy _the entire_ AA every time it's referenced. But it's not just AA's. 
> Normal arrays have the problem too.
> 
> Given that the value of enum must be known at compile time and given that it 
> cannot be changed, why aren't enums all immutable? What's gained by making so 
> that every reference to an enum is replaced by its value rather than actually 
> referencing an immutable value? In most cases, it could still be replaced by 
> the value (since it's a constant) if that's more efficient. And in the case of 
> reference types, it would actually act like a reference type.
> 
> So, I ask, should enums just all be made automatically immutable instead of 
> having the current replace when referenced semantics? Is there a good reason 
> _not_ to make all enums immutable?

Yes. The ONLY reason those manifest constants exist at all, is so that 
they don't exist at run time. They have no address. Any case where 
taking a reference to them works, is a compiler bug.

Almost all existing enum arrays or AAs are bugs.
For example, if you have a lookup table which should be used at runtime, 
it should ALWAYS be defined as const or immutable, not as an enum.


More information about the Digitalmars-d mailing list