How to call destructor before free without dropping @nogc?
Bienlein
ffm2002 at web.de
Thu Aug 19 07:30:38 UTC 2021
Hello,
I allocate some instance of class C manually and then free the
memory again:
class C {
int num;
~this() {
writeln("~this");
}
}
void foo() // @nogc
{
auto mem = cast(C)malloc(__traits(classInstanceSize, C));
auto c = emplace!(C)(mem);
c.num = 789;
destroy(c);
free(cast(void*) c);
c = null;
}
int main()
{
foo();
}
The code above works well as the destructor of c in class C is
called by destroy. Problem is that destroy cannot be used once
function foo is annotated with @nogc. There seems to be no way
round it.
What I want is to keep the function foo annotated with @nogc, but
still have the destructor of C be called before free is called.
Is there a way to call the destructor through meta programming or
some kind of reflection so that I can create some generic
function that calls the destructor and then free for any kind of
class?
Thanks, Bienlein
More information about the Digitalmars-d-learn
mailing list