const and immutable members

anonymous anonymous at example.com
Sun Sep 22 13:43:30 PDT 2013


On Sunday, 22 September 2013 at 16:15:09 UTC, Daniel Davidson 
wrote:
[...]
>>> 3) Also, is storing immutable(STUFF) in a struct in the 
>>> general
>>> case (as opposed to just this one) useful or silly?
>
[...]
>
> I don't really understand the _tail-const_, _tail-immutable_ 
> argument. Why is _tail-const_ fine but not _const_ when there 
> is transitivity anyway?
>
[...]
>
> 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.

By marking the tail of the member const -- e.g. const(int)[] --, 
you're committing to not altering the refered-to data. This 
means, the user of your struct can put in mutable and immutable 
data.

When you mark it full-const -- const(int[]) -- you're taking away 
from the user the ability to make it refer to some other data. In 
particular, setting a variable of your struct type to a new value 
requires mutable members. There may be special cases where that 
extra restriction is desired, but I can't think of one. Unless 
you're in such a special case, it just hurts the user for no 
reason.

And when the user needs a const object, they can do that on their 
own:
struct S {int x;}
const s = S(42);
static assert(is(typeof(s.x) == const));


More information about the Digitalmars-d-learn mailing list