On Thursday, 19 August 2021 at 07:30:38 UTC, Bienlein wrote:
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
Oops, I just realized that you can also not call emplace when
@nogc is present. Well that is at least consistent with not
either being able to call destroy ;-).
So, I guess this means that you can forget about manually
allocating and freeing some instance of a class and using @nogc
as well. That's a pitty, @nogc was a good idea.