Wrong const attribute?

Jonathan M Davis jmdavisProg at gmx.com
Thu Sep 22 10:12:42 PDT 2011


On Thursday, September 22, 2011 04:12 Paolo Invernizzi wrote:
> Hi all,
> 
> I've found nothing on bugzilla for that, what I'm missing? Or it's a bug?
> (DMD 2.055)
> 
> struct Bar {
> immutable int i;
> this(int j){ i = j; }
> }
> 
> struct Foo {
> Bar bar;
> }
> 
> void main(){
> 
> auto b = Bar(1);
> 
> auto f = Foo();
> f.bar = Bar(2); // Error: can only initialize const member bar inside
> constructor
> 
> }

The error is a bit confusing but essentially correct. Bar has an immutable 
member variable. Once it's been initialized, that immutable member variable 
can never be changed, so you can never assign to a variable of type Bar. 
Naturally, that includes the member variable in Foo. So, when you constructed 
your f variable, the bar member variable was initialized, and after that, it 
can never be assigned to. So, when you try and do it, you get an error. The 
error message could definitely use some improvement though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list