Practical difference between a struct with const members and with mutable members?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 9 09:38:27 PDT 2016


On 09.04.2016 18:07, pineapple wrote:
> What's different between these two examples, practically speaking? When
> would you use one over the other?
>
> struct thing1{
>      const int x, y;
> }
>
> struct thing2{
>      int x, y;
> }

In this case, const is practically the same as immutable. But immutable 
is the stricter qualifier. It's more self-documenting, and it may be 
simpler to utilize for the compiler in terms of optimizations. So I'd 
use immutable instead of const here. Differences between const and 
immutable manifest with indirections (pointers, arrays, classes, ...).

The effect of const (or immutable) in thing1 is simple: you can't mutate 
its x or y after construction. Whereas thing2 allows mutation of its x 
and y.

In code:
----
thing1 t1;
t1 = thing1(1, 2); /* doesn't compile; the fields of t1 are immutable */

thing2 t2;
t2 = thing2(1, 2); /* compiles */
----

You can do the same with thing2 on a per-object basis:
----
immutable thing2 t2i;
t2i = thing2(1, 2); /* doesn't compile; t2 is immutable */
----

For a struct like thing1 that just has some value type members, I don't 
see a point in making all the members const/immutable. Making the 
instances const/immutable instead is more versatile.

const is generally more useful when references are involved (pointers, 
arrays, classes, ...).


More information about the Digitalmars-d-learn mailing list