Why do immutable variables need reference counting?

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


On 4/12/22 12:54, wjoe wrote:

 > I.e. immutable is constant data which is created at compile time - like
 > laws of physics,

For completeness, we already have 'enum' and 'static const' for that.

 > should get a better name - maybe 'in' and get rid of const.

Yes! 'in' for parameters! :D

 >> import std.stdio;
 >> import std.format;
 >>
 >> struct S {
 >>   const(char)[] fileName;
 >>
 >>   this(const(char)[] fileName) {
 >>     this.fileName = fileName;
 >>     report();
 >>   }
 >>
 >>   ~this() {
 >>     report();
 >>   }
 >>
 >>   void report(string func = __FUNCTION__) {
 >>     writefln!"%s working with %s."(func, fileName);
 >>   }
 >> }
 >>
 >> void main() {
 >>   char[] fileName = "foo.txt".dup;
 >>   auto s = S(fileName);
 >>   fileName[0..3] = "bar";
 >> }
 >>
 >>
 >> If fileName were immutable, then the owner would not be able to mutate
 >> anyway, so the struct could get away without copying the file name.
 >>
 >> Ali
 >
 > I presume you refer to fileName in main() ?

No, I meant the member 'fileName'. If the member is 'const' (as in C++ 
and as in the example above), you have to take a copy because the caller 
may mutate. (The example is demonstrating the case where the struct 
assumes data won't changed and gets surprised by the mutation.)

 > And if yes, if it were
 > const, it couldn't be mutated either,

You started as assuming 'fileName' in main, so, I will continue with 
that. If the struct had 'const fileName' and pleaded that the caller 
also define a 'const' variable, that would be wishful thinking. The 
struct cannot trust that all callers will obey that plea.

That kind of trust (more like guarantee) comes with 'immutable' and this 
is a good example of how immutable is different from const. (immutable 
does not exist in some languages like C++.)

 > so isn't immutable and const sort
 > of synonymous in that case or am I missing your point?

If on the other hand, the member were immutable, the caller would have 
to provide immutable data and the struct could rely on the fact that the 
data was immutable forever. No need for a copy...

Ali



More information about the Digitalmars-d-learn mailing list