enum VS static immutable
Ali Çehreli
acehreli at yahoo.com
Thu Mar 13 10:33:31 PDT 2014
On 03/13/2014 07:38 AM, ref2401 wrote:
> Hi.
> I have this structure:
>
> struct MyStruct {
> enum MyStruct VALUE = MyStruct(5f);
>
> static immutable MyStruct value = MyStruct(5f);
>
>
> float data;
>
> this(float v) { data = v; }
> }
>
> What's the difference between MyStruct.VALUE and MyStruct.value? How
> should I decide what to use?
enum defines a manifest constant, meaning that it is just a value; there
is not one but many MyStruct objects constructed every time VALUE is
used in the code. The following run-time asserts prove that two
instances have different data members:
assert(&MyStruct.VALUE.data != &MyStruct.VALUE.data);
On the other hand, there is just one MyStruct.value object:
assert(&MyStruct.value == &MyStruct.value);
In other words, MyStruct.VALUE is an rvalue but MyStruct.value is an
lvalue; you cannot take the address of an rvalue. The following static
asserts pass.
static assert(!__traits(compiles, &MyStruct.VALUE));
static assert( __traits(compiles, &MyStruct.value));
It shouldn't matter much for such a type but prefer a static immutable
for expensive types like arrays.
Ali
More information about the Digitalmars-d-learn
mailing list