This is bug or not? (immutable class containing struct with dtor)

Ali Çehreli acehreli at yahoo.com
Fri Dec 17 18:51:56 UTC 2021


On 12/17/21 10:01 AM, Tejas wrote:

 > I think since `immutable` objects are kept in Read Only Storage,

There is no such requirement nor guarantee.

 > you
 > can't call destructors on them

Destructor is nothing but a piece of code that is executed when an 
object's life ends. A destructor need not touch any member of the object:

struct S {
   ~this() {
     import std.stdio;
     writeln("done");
   }
}

void main() {
   immutable a = S();
   auto b = immutable(S)();
}

Both objects are immutable there yet their destructor is executed.

 > since the objects don't get erased when
 > `~this` is called, but rather they get assigned their `.init` value,

That's true only for destroy(), which gets called only if the programmer 
asks for it. Otherwise, destroyed objects don't get assigned any special 
value.

 > which tells the GC that they can be collected.

That's not true. The GC collects objects when there are no references to 
them. The values of the object's members have nothing to do with it.

 > `immutable class` has nothing to do with it, even the following fails to
 > compile:
 > ```d
 >
 >
 >
 > struct S
 > {
 >      ~this() immutable {}

That immutable qualifier means "this destructor is for immutable objects 
of this type." However, it seems impossible to define two destructors:

   ~this() {
     writeln(__FUNCTION__);
   }

   ~this() immutable {
     writeln(__FUNCTION__);
   }

Error: destructor `deneme.S.~this` conflicts with destructor 
`deneme.S.~this` at deneme.d(79)

I think this is an unexplored corner of the language. Part of the 
complication may be due to implementations by an earlier compiler 
contributor, who I heard was responsible for qualifiers on constructors. 
Note two different constructors here:

import std.stdio;

struct S {
   this(int) {
     writeln(__PRETTY_FUNCTION__);
   }

   this(int) immutable {
     writeln(__PRETTY_FUNCTION__);
   }
}

void main() {
   auto a = immutable(S)(0);
   auto b = S(1);
}

I bet the problem here is that the implementation in the compiler is 
half-baked on these qualifiers.

Ali



More information about the Digitalmars-d-learn mailing list