Why do immutable variables need reference counting?

Ali Çehreli acehreli at yahoo.com
Tue Apr 12 16:59:15 UTC 2022


On 4/12/22 03:28, Dom DiSc wrote:
 > On Monday, 11 April 2022 at 22:10:07 UTC, Ali Çehreli wrote:
 >> 1) I will not mutate data through this reference. For example, a
 >> parameter that is pointer to const achieves that:
 >>
 >>   void foo (const(int)[] arr);
 >>
 >> 2) This variable is const:
 >>
 >>   const i = 42;
 >>
 >> Well, there is the confusion: There is no "reference" in the second
 >> case at all!
 > I think this second case should not be allowed. Use
 >
 >     immutable i = 42;
 >
 > instead. The meaning is identical,

Only if there are no indirections as in 'int'. If I use a struct

struct S {
   const(char[]) arr;
}

void foo(const(char[]) arr) {
   immutable s = immutable(S)(arr);  // <-- ERROR:
   // Error: cannot implicitly convert expression `arr` of type 
`const(char[])` to `immutable(string)`
}

void main() {
   int[] arr;
   foo(arr);
}

The reason is a property of immutable that I like to describe as 
"selective" (or "demanding"). The struct variable cannot be immutable 
because it would be demanding that its constructor argument be 
immutable, which cannot be because foo's 'const' parameter hides that 
information even when it were immutable e.g. in main().

 > but we could remove the burden of two
 > different meanings from const if it is not allowed. const should only be
 > allowed in function declarations. A variable must be declared either
 > mutable or immutable. It's only functions that may guarantee not to
 > modify a parameter or the objects they belong to, and so are allowed to
 > work on both mutable and immutable objects.

I understand but the guarantee of immutable seems to leave no other choice.

Ali



More information about the Digitalmars-d-learn mailing list