Classes as enums in D?
Marc Schütz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 30 02:22:53 PST 2015
On Monday, 30 November 2015 at 08:08:20 UTC, Meta wrote:
> class WhiteKey
> {
> private immutable int halfStepsToNext;
> private immutable int halfStepsToPrevious;
>
> enum
> {
> A = new WhiteKey(2, 2),
> B = new WhiteKey(2, 1),
> C = new WhiteKey(1, 2),
> D = new WhiteKey(2, 2),
> E = new WhiteKey(2, 1),
> F = new WhiteKey(1, 2),
> G = new WhiteKey(2, 2),
> }
>
> private this(int halfStepsToPrevious, int halfStepsToNext)
> {
> this.halfStepsToPrevious = halfStepsToPrevious;
> this.halfStepsToNext = halfStepsToNext;
> }
> }
>
> However, you do NOT want to do this, as everywhere you use
> WhiteKey's members, a new object will be created. For example:
>
> auto f = WhiteKey.A;
> auto n = WhiteKey.A;
>
> import std.stdio;
> writeln(&f, " ", &n);
>
You're misinterpreting this:
enum X {
A = new Object,
B = new Object,
}
void main() {
import std.stdio;
writeln(cast(void*) X.A);
writeln(cast(void*) X.A);
}
# output:
470910
470910
You're print the address of `f` and `n` on the stack, not the
reference they're pointing to.
But it's true that enums of mutable _arrays_ do create a new
instance every time they're used:
enum X {
A = [1,2,3],
B = [4,5,6],
}
void main() {
import std.stdio;
writeln(X.A.ptr);
writeln(X.A.ptr);
}
# output:
7FD887F0E000
7FD887F0E010
More information about the Digitalmars-d-learn
mailing list