Constructor qualifiers; bug or expected behavior?

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Apr 2 16:58:11 UTC 2018


On Mon, Apr 02, 2018 at 10:26:32AM +0000, RazvanN via Digitalmars-d-learn wrote:
> Hi all,
> 
> Let's say we have this code:
> 
> struct B
> {
>     int a;
>     this(int a) immutable
>     {
>         this.a = 7;
>     }
> 
>     this(int a)
>     {
>         this.a = 10;
>     }
> }
> 
> void main()
> {
>     B a = immutable B(2);
>     writeln(a.a);
>     a.a = 4;
> 
>     immutable B a2 = immutable B(3);
>     writeln(a2.a);
>     a2.a = 3;        // error : cannot modify
> }
> 
> Both a and a2 will be constructed using the immutable constructor,
> however a is not immutable (a.a = 4 will compile fine). Is this the
> intended behavior?
> Shouldn't the compiler warn me that I'm trying to create a mutable
> object using the constructor for an immutable object? I couldn't find
> any documentation about this.

What's happening here is that B is a value type, meaning that assignment
makes a copy of the object. Since B has no fields that contain
indirections, when a copy of B is made, it is completely independent of
the original immutable object, so it's perfectly fine to make the copy
mutable.


T

-- 
Meat: euphemism for dead animal. -- Flora


More information about the Digitalmars-d-learn mailing list