Should all enums be immutable?
Nick Sabalausky
a at a.a
Tue Apr 5 16:53:35 PDT 2011
"Rainer Schuetze" <r.sagitario at gmx.de> wrote in message
news:ind21j$1si5$1 at digitalmars.com...
>
> Don wrote:
>> 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.
>
> Unfortunately, you currently get the same performance penalty with const
> or immutable arrays as with enum:
> http://d.puremagic.com/issues/show_bug.cgi?id=4298
What about "enum string x = ..." or "immutable string x = ..."? Anyone know
if those exhibit the same problem?
More information about the Digitalmars-d
mailing list