class destructors must be @disabled?
Ali Çehreli
acehreli at yahoo.com
Wed May 18 19:58:09 UTC 2022
On 5/18/22 12:45, Steven Schveighoffer wrote:
> Not cleaning it up because you're afraid of destructors is not the
answer.
Fine. The GC allocation issue remains. It looks like one of the
following should be observed:
a) @disable ~this() for all classes so that we are safe from the
destructors of otherwise-well-written struct members as well. In
general, this option requires a cleanup function for the class, which
should be called at an opportune moment before its memory is freed by
the GC.
b) Consider GC.inFinalizer() in every struct destructor that has any
chance of being used in a class. This may not work for all structs (see
below).
c) Extend the "do not allocate GC memory in the destructor" guideline to
all structs.
Do not allocate memory in such conditions, which may be problematic
because my example would make every struct object expensive by holding
on to a string prepared before hand to be used in the destructor:
struct S {
int id;
string closingMessage; // <-- Expensive
this(int id) {
this.id = id;
this.closingMessage = format!"%s signing off"(id);
}
~this() {
// No allocation in the destructor; good.
closeConnection(closingMessage);
}
}
The non-expensive solution is to use a @nogc solution like sprintf?
Hmm. Perhaps the guideline should be "all destructors must be @nogc".
Ali
More information about the Digitalmars-d-learn
mailing list