Immutable fields

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 2 19:19:09 PDT 2010


On Tuesday 02 November 2010 17:54:35 bearophile wrote:
> Is it correct for immutable struct fields to act like enum or static const
> fields? (I don't think so, but I am wrong often):
> 
> struct Foo {
>     immutable int x = 1;
> }
> static assert(Foo.sizeof == 4);
> void main() {}
> 
> 
> More info in the D.learn thread:
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.l
> earn&article_id=22540
> 
> Thank you,
> bearophile

Assuming that it's the constructor which initializes the variable, then it's 
going to have to have storage, immutable or not. However, if it's not set by the 
constructor but directly initialized, then I don't see why the compiler can't 
treat it as not having storage. At that point, it's conceptually the same as 
using an enum. Why would it really matter though? If anything, I would have 
thought that the elimination of the storage would be a good thing, since it 
reduces the memory footprint of the object.

- Jonathan M Davis


More information about the Digitalmars-d mailing list