Mutable enums
so
so at so.so
Sun Nov 13 18:03:54 PST 2011
On Mon, 14 Nov 2011 02:50:50 +0200, Jonathan M Davis <jmdavisProg at gmx.com>
wrote:
> No. Those are two _very_ different things.
>
> immutable a = [3, 1, 2];
>
> creates a variable of type immutable(int[]). You takes up memory. You
> can take
> its address - e.g. &a. It exists even if you don't use it at all.
>
> enum a = [3, 1, 2];
>
> on the other hand, doesn't create any variable at all. It's what's
> called a
> manifest constant. It's a placeholder. It takes up no memory. You can't
> take
> its address. If you never use it, it doesn't end up in the generated
> program
> at all. Every use of a effectively copies the value of a to wherever its
> used.
> So,
>
> enum a = [3, 1, 2];
> sort(a);
>
> is _identical_ to
>
> sort([3, 1, 2]);
>
> That means that if you use a in any code, it's copied in that code such
> that
> you could end up allocating a lot of memory that you didn't intend to if
> you
> heavily use manifest constants which are strings or arrays. But it also
> means
> that you get a new copy to use at each location, which can also be
> useful. And
> for types that don't end up on the heap (e.g. int), there's really no
> cost to
> it, and it actually is _more_ efficient (albeit marginally), since it
> avoids
> having to allocate any memory for the enum itself, since it's not a
> variable.
>
> - Jonathan M Davis
Trying to remember the discussions on digitalmars.D regarding
enum/immutable. There were contradicting opinions.
You ask the same question at two different times, you get at least two
different answers, especially on this matter.
There was/is not a consensus on how it works or should work.
While i think enum/immutable are not same thing. Because with enum you
mean it is a compile time value and compile time only, but immutable might
rely on runtime initializers. So it differs here. This just means enum
gives you more guaranties, not less.
enum a = 5;
immutable b = 6;
a = 3;
b = 3;
If the above code is invalid for both enum and immutable, so should the
"in-place" sort case. I understand how it works, but it doesn't make any
sense why it should work that way.
More information about the Digitalmars-d-learn
mailing list