const and immutable members

Daniel Davidson nospam at spam.com
Sun Sep 22 09:15:08 PDT 2013


In this thread 
(http://forum.dlang.org/thread/uvhwkgljavskqfueqyxo@forum.dlang.org) 
I asked this:

>> 3) Also, is storing immutable(STUFF) in a struct in the general
>> case (as opposed to just this one) useful or silly?

Johnathan M Davis replied:

> As soon as you have a const or immutable member in a
> struct, you can't ever assign anything to it, even if
> all of its other members are mutable (you could
> assign the individual, mutable members but not the
> whole struct). That means stuff like if the struct is
> ever default-initialized, you can't even give it
> another value, which tends to mean that you can't use
> such a struct in places like arrays.
>
> All in all, I think that it's pretty much always a
> bad idea to have a struct with const or immutable
> members. It's just begging for problems. Tail-const
> or tail-immutable is fine, because the members
> themselves aren't const or immutable (just what they
> refer to), but having them be directly const or
> immutable is a bad idea IMHO.


I don't really understand the _tail-const_, _tail-immutable_ 
argument. Why is _tail-const_ fine but not _const_ when there is 
transitivity anyway?

I think there are only a handful of places you consider using 
const/immutable:

- Global variables
- Local variables
- Member variables
- Function signatures

Are there any missing?

If right out of the gate the feeling is member variables should 
not be const or immutable, doesn't that greatly reduce the value 
of the mutability specificiers? Members are used to hold onto the 
data for the lifecycle of the object and if those should not make 
claims or guarantees on mutability then that seems a shame.

What do others think?
Are there cases where const/immutable members are being used in a 
good way?

In that thread I gave a motivation for it (I used emacs and the 
formatting turned out awful - so sorry about that). But not sure 
if my logic holds water.

Thanks
Dan


More information about the Digitalmars-d-learn mailing list