pure and custom new / delete
Steven Schveighoffer
schveiguy at yahoo.com
Tue Jun 26 10:19:37 PDT 2012
On Tue, 26 Jun 2012 12:05:55 -0400, Benjamin Thaut
<code at benjamin-thaut.de> wrote:
> Am 26.06.2012 18:02, schrieb Timon Gehr:
>> You can cast function pointers to pure, or mark extern(C) memory
>> allocation functions as pure.
>
> extern(c) is not an options as there is a structure of various different
> allocators that implement a common interface which all is written in D.
extern(C) does not mean implemented in C, it just means C linkage. You
can use arrays, classes, etc. in extern(C) functions. UFCS makes this
really easy too:
myalloc.d:
interface Allocator
{
void * _alloc(size_t size);
}
extern(C) void *alloc(Allocator a, size_t size) pure;
allocimpl.d:
import myalloc;
extern(C) void *alloc(Allocator a) // pure
{
return a._alloc(size)
}
mallocer.d:
public import myalloc;
import std.c.stdlib;
// sample allocator
class Mallocer : Allocator
{
void *_alloc(size_t size) { return malloc(size);}
}
main.d:
import mallocer;
void foo(Allocator a) pure
{
a.alloc(200);
//a._alloc(200); // fails as expected
}
void main()
{
foo(new Mallocer);
}
-Steve
More information about the Digitalmars-d
mailing list