Class qualifier vs struct qualifier

David Bennett davidbennett at bravevision.com
Fri Jun 15 06:26:41 UTC 2018


On Wednesday, 13 June 2018 at 07:35:25 UTC, RazvanN wrote:
> Hello,
>
> I'm having a hard time understanding whether this inconsistency 
> is a bug or intended behavior:
>
> immutable class Foo {}
> immutable struct Bar {}
>
> void main()
> {
>     import std.stdio : writeln;
>     Foo a;
>     Bar b;
>
>     writeln("typeof(a): ", typeof(a).stringof);
>     writeln("typeof(b): ", typeof(b).stringof);
> }
>
> prints:
>
> typeof(Foo): Foo
> typeof(Bar): immutable(Bar)
>
>
> It seems like the class storage class is not taken into account 
> which leads to some awkward situations like:
>
> immutable class Foo
> {
>     this() {}
> }
>
> void main()
> {
>     Foo a = new Foo(); // error: immutable method `this` is not 
> callable using a
>                        // mutable object
> }
>
> To make it work I have to add immutable to both sides of the 
> expression : immutable Foo a = new immutable Foo(); this is a 
> wonder of redundancy. I already declared the class as immutable 
> so it shouldn't be possible to have mutable instances of it 
> (and it isn't), however I am forced to write the immutable 
> twice even though it is pretty obvious that the class cannot be 
> mutated.

Just tested and I only seem to need to add the immutable to the 
left of the expression.

https://run.dlang.io/is/EZ7es0

Also with the struct `Bar* b = new Bar();` works fine so i guess 
the discrepancy is because the class ref is mutatable.


More information about the Digitalmars-d-learn mailing list