Can't I allocate at descontructor?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Mar 5 21:02:08 UTC 2021


On Fri, Mar 05, 2021 at 08:24:26PM +0000, Jack via Digitalmars-d-learn wrote:
> On Friday, 5 March 2021 at 20:18:44 UTC, Max Haughton wrote:
> > On Friday, 5 March 2021 at 20:13:54 UTC, Jack wrote:
[...]
> > > But the ones heap may never run at all, is that right?
> > 
> > You can't rely on the garbage collector for deterministic
> > destruction, no.
> 
> Are there some kind of replacement or I have to make my own
> finalize-like method, once I determine somewhat the application no
> longer need those resources?
[...]

If you know when you can deallocate something, that means you don't need
the GC to collect it, so you could just allocate it on the malloc heap
instead, and call destroy/free once you're done.  You could use the C
version of malloc/free.  You can also optionally use GC.malloc/GC.free.

E.g.:

	class C {...}

	import core.memory : GC;
	C c = cast(C) GC.malloc(C.sizeof);
	... // use c

	// We're done with c, destroy it
	destroy(c);	// this will call the dtor
	GC.free(cast(void*) c);
	c = null; // optional, just to ensure we don't accidentally use it again


T

-- 
Freedom of speech: the whole world has no right *not* to hear my spouting off!


More information about the Digitalmars-d-learn mailing list