@safe containers with std.experimental.allocator

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Sat Jan 21 02:15:46 PST 2017


On Saturday, 21 January 2017 at 09:56:29 UTC, ZombineDev wrote:
> 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
>
> There's no need for casts. You can just use the high-level 
> wrappers:
> http://dlang.org/phobos-prerelease/std_experimental_allocator#.make
>
> http://dlang.org/phobos-prerelease/std_experimental_allocator#.makeArray
>
> http://dlang.org/phobos-prerelease/std_experimental_allocator#.dispose
>
> http://dlang.org/phobos-prerelease/std_experimental_allocator#.makeMultidimensionalArray
>
> http://dlang.org/phobos-prerelease/std_experimental_allocator#.disposeMultidimensionalArray

Though, since you are implementing a container that manually 
manages memory, you won't be able to get away with no @trusted 
parts in your code. 
http://dlang.org/phobos-prerelease/std_experimental_allocator#.expandArray can help, but you'll still need to call dispose/deallocate somewhere yourself and you're the only that knows when is safe to do this.
If you look at how Rust's standard library is implemented, you'll 
see the same pattern. The users have a safe API, but underneath 
you'll that the library uses many 'unsafe' blocks where the 
compiler doesn't see the full picture which only the author of 
the code knows.


More information about the Digitalmars-d mailing list