@safe containers with std.experimental.allocator

Eugene Wissner via Digitalmars-d digitalmars-d at puremagic.com
Fri Jan 20 21:06:07 PST 2017


On Saturday, 21 January 2017 at 02:47:49 UTC, bitwise wrote:
> When std.experimental.allocator was created, I was under the 
> impression it was meant to be used to make containers. But 
> since allocate() returns void[], casts are required before 
> using that memory, which is unsafe.
>
> Is my only option to wrap the casts in an @trusted helper 
> function? or am I missing something?
>
>  Thanks

System functions that do memory allocation, give you a memory 
block as a void*. So a cast is anyway required to cast to the 
required data type.

Allocators don't cast from void* because you would need to 
implement the same logic in each allocator. Therefore there are 
functions like make/makeArray/dispose that take an allocator, 
cast and initialize data.

As for safity part. Allocators can't provide the same safity as 
the garbage collector anyway, because if you use manual memory 
management you get all the problems like you can pass to 
deallocate() a wrong pointer or to free a memory block twice. But 
with the right abstractions and enough testing, you can reduce 
such problems and make the code more trusted.

Alligned allocator isn't present in the 
std.experimental.allocator because IAllocator has a method 
alignedAllocate() (or similar) - so any allocator can be designed 
to provide aligned allocations.


More information about the Digitalmars-d mailing list