@safe containers with std.experimental.allocator

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Sat Jan 21 09:06:14 PST 2017


On Saturday, 21 January 2017 at 10:15:46 UTC, ZombineDev wrote:
> 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.

I guess you're right. This is my first time looking at @safe in 
detail. I figured something like malloc() could @trusted, but I 
suppose free cannot.

I pictured being able to use an @safe allocator with an @safe 
container. How else could one reliably create @safe containers, 
or any @safe object for that matter, that allows the substitution 
of arbitrary and possibly unsafe components?

I guess the answer is responsible programming, but that seems 
counter intuitive given the goals of @safe.



More information about the Digitalmars-d mailing list