Clarifcation on AA allocation
Sean Kelly
sean at f4.ca
Sat Apr 8 17:32:31 PDT 2006
pragma wrote:
> Is there any way to 'manually' allocate memory for an AA in D?
>
> The problem that prompted me to ask this? Well, I have a class that maintains a
> set of HANDLES using an AA. Ideally, I'd like to be able to free these using
> the class' dtor(), but isn't there the possibility that the GC will eliminate
> the AA's memory before the dtor() is even called?
>
> I suppose I could instruct the GC to 'ignore' the AA via 'removeRange' for
> safety reasons, but I'd like to know if anyone else has a more elegant solution?
I thought about this for a while and was surprised to conclude that
there's no good and easy eay to do this in D. In an ideal world you
could use a struct and put the cleanup code in the struct's dtor, but
that's obviously not an option. If you're willing to settle for an easy
solution, RAII via classes would work:
class HandleWrapper
{
HANDLE val;
this( HANDLE h) { val = h; }
~this() { CloseHandle( val ); }
HANDLE opCast() { return val; }
}
This will give you poor locality and a good bit of memory overhead (more
than twice that of the struct method), but it's a darn sight simpler
than the alternatives.
For a while I thought maybe something could be sorted out via an AA of
static arrays or fixed-size structs and allocating classes on top of
them via placement new, but this would require .isizeof (which I
mistakenly submitted as an enhancement to the bug list yesterday), and
would still likely either result in premature cleanup of the objects or
in their dtors never being called. Also, it doesn't sit well with me
that the objects would be copied around by the AA code with no copy ctor
being called... even if one isn't strictly necessary in this case.
The only reasonable alternative I could come up with would be to use a
non-local allocator to store the handles and to simply index them via
the AA in your class. But this probably isn't worth doing unless you
have memory size or performance issues that can be traced back to the AA.
Sean
More information about the Digitalmars-d-learn
mailing list