www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - enum VS static immutable

reply "ref2401" <refactor24 gmail.com> writes:
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?
Mar 13 2014
next sibling parent reply "w0rp" <devw0rp gmail.com> writes:
On Thursday, 13 March 2014 at 14:38:27 UTC, 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 is a compile-time constant. 'static immutable' is an immutable (and therefore implicitly shared between threads...) runtime constant that isn't part of the struct itself. I'd stick with enum and switch to static when what you're writing becomes impossible to express at compile-time. A surprising number of things can actually be expressed at compile-time.
Mar 13 2014
parent "ref2401" <refactor24 gmail.com> writes:
thank you
Mar 13 2014
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
Mar 13 2014