Phobos 3 Discussion Notes - 02-01-2024

ryuukk_ ryuukk.dev at gmail.com
Wed Feb 7 11:29:04 UTC 2024


On Wednesday, 7 February 2024 at 10:10:27 UTC, Atila Neves wrote:
> On Wednesday, 7 February 2024 at 05:55:04 UTC, Paul Backus 
> wrote:
>> On Tuesday, 6 February 2024 at 14:41:27 UTC, Martyn wrote:
>>> Curious to know how this will work for D. Will Allocators be 
>>> available for BetterC as well? I certainly hope so!
>>
>> Nothing's set in stone yet, but in the proposal I'm working 
>> on, there is nothing stopping allocators from being available 
>> in BetterC.
>>
>>> If so, I guess the **default** Allocator will be the GC one, 
>>> and can still be disabled. Being able to change the default 
>>> (or change locally like in a function or pass it as 
>>> parameter) would provide a lot of flexibility.
>>
>> In my proposal, when you use a library container (like an 
>> array, a hash table, a binary tree, etc.), you can specify 
>> what type of allocator you want to use as a template parameter 
>> (as in, `Array!(int, GC)`). It will probably default to the 
>> GC, but you can just as easily use malloc, or even a custom 
>> allocator that you write yourself.
>>
>> I'm not planning to include a global default allocator. 
>> Built-in language features like `new`, dynamic arrays, 
>> associative arrays, and delegate contexts will always use the 
>> GC, and there will not be an option to change this.
>
> The problem with this approach, as C++ found out, is that 
> `Vector!(int, MyAlloc)` is a different type from `Vector!(int, 
> YourAlloc)`. The way I got around that is by defaulting to a 
> global allocator. This has its drawbacks as well of course, 
> because now everything is a virtual call.

I do that as well

```D
struct Array(T)
{
     T[] items;
     Allocator allocator;
     size_t count = 0;
```


Just store the allocator in the struct, it's no big deal, granted 
your allocator type is a simple and compact struct

```D
struct Allocator
{
     void* ptr;
     AllocatorFN* fn;
}
struct AllocatorFN
{
     alloc_d alloc;
     resize_d resize;
     free_d free;
}

// libc
enum c_allocator = Allocator(null, &CAllocator.fn);
struct CAllocator
{
     __gshared AllocatorFN fn = {
         alloc: &alloc_impl,
         resize: &resize_impl,
         free: &free_impl
     };
}
```

That's it

```D

Allocator heap = c_allocator;

auto entities = Array!(Entity).create(heap);

```



More information about the Digitalmars-d mailing list