Mallocator
Erik Smith via Digitalmars-d
digitalmars-d at puremagic.com
Thu Mar 3 11:01:52 PST 2016
Just a question on Mallocator and shared. My code does a lot of
non-GC heap allocation (malloc) for buffers, so I reached for
Mallocator as a starting point. I propagate an Allocator type
generically through my structs, but it is defaulted to Mallocator.
After checking with the docs & TDPL, I'm still a bit confused on
how to deal with the shared functions in Mallocator and what the
effect of shared functions is in this context (see code below). I
get the error "allocate is not callable using a non-shared
object" and I'm not sure how to resolve it. I'm not sure if I
should cast shared away (or how to make that work). The docs say
malloc/free is thread safe as far as D is concerned, so
synchronized doesn't seem to be the answer. Forking Mallocator
without shared solved the issue temporarily.
Also Allocators are, in general, not copyable so I should
propagate them around as references (or pointers in struct
members), correct?
struct Mallocator{
...
@trusted @nogc nothrow
void[] allocate(size_t bytes) shared
{
import core.stdc.stdlib : malloc;
if (!bytes) return null;
auto p = malloc(bytes);
return p ? p[0 .. bytes] : null;
}
@system @nogc nothrow
bool deallocate(void[] b) shared
{
import core.stdc.stdlib : free;
free(b.ptr);
return true;
}
...
}
More information about the Digitalmars-d
mailing list