Class qualifier vs struct qualifier

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jun 14 17:07:09 UTC 2018


On Thursday, June 14, 2018 08:39:48 RazvanN via Digitalmars-d-learn wrote:
> > Honestly, from what I understand of how this works, what I find
> > weird is the struct case. immutable on classes does _not_ make
> > the class itself immutable. It just makes all of its members
> > immutable - hence the error about trying to allocate new Foo
> > instead of new immutable Foo. So, that is exactly what I would
> > expect. And honestly, being able to write Foo and have it imply
> > immutable Foo would get _really_ confusing when reading and
> > debugging code.
>
> Maybe it has something to do with structs being value types and
> classes
> being reference types. If you declare an immutable struct then
> you cannot
> modify it's value, while if you declare a class, the pointer to
> the class
> is mutable, while the class fields are not. This kind of makes
> sense, however
> the thing is that in both situations you are not able to mutate
> any of the
> class/struct fields no matter how you instantiate it, so it is
> really redundant
> to use `immutable` when creating the instance.

Except that it isn't redundant, because without using immutable, it looks
like you're trying to create a mutable object. Would you honestly ever look
at something like

Foo foo;

and expect the object to be immutable? And sadly, looking at the type
declaration isn't even necessarily enough to know that it was marked with
immutable, because someone could have done something dumb like put

immutable:

higher up in the file. Types normally require that you explicitly mark them
as immutable to make them immutable when using them anywhere - including
declaring variables or allocating objects. I don't see why having made all
of the members of the type immutable should change that. It's just extra
magic that makes it harder to read the code. Sure, it would save you a
little bit of typing when you do something like

auto foo = new Foo;

if makes it immutable for you, but it's at the cost of code clarity.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list