What are (dis)advantages of using pure and immutable by default?
Bahman Movaqar via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 7 05:07:15 PDT 2015
On Monday, 7 September 2015 at 11:49:32 UTC, anonymous wrote:
> void f(int a) {}
> void g(int* a) {}
>
> void main()
> {
> int xm;
> immutable int xi;
> f(xm); /* ok, obviously */
> f(xi); /* ok */
>
> int* ym = &xm;
> immutable int* yi = ξ
> g(ym); /* ok, obviously */
> g(yi); /* doesn't compile */
> }
> ----
>
> f(xi) is ok because when passing an int or an immutable(int),
> it's copied completely. So the f cannot possibly mutate the
> original immutable variable xi.
>
> g(yi) is not ok, because when passing an int* or an
> immutable(int*), only the pointer is copied. So g could
> dereference yi and mutate the referenced immutable variable xi.
>
> The same applies to other forms of references: classes, ref
> parameters, arrays.
Thanks for the explanation.
So from what I can gather, `immutable`, apart from possible
compiler-level optimisations, is mainly there to help the
programmer catch otherwise runtime errors at compile time.
This is nice. Indeed very helpful in a language when one deals
with pointers and references.
More information about the Digitalmars-d-learn
mailing list