On Sunday, 9 April 2017 at 13:59:14 UTC, Andrei Alexandrescu wrote:
On 4/9/17 4:56 AM, Atila Neves wrote:
Using std.experimental.allocator? Tired of writing `scope(exit) allocator.dispose(foo);` in a language with RAII? Me too:




http://code.dlang.org/packages/automem

Example:

I think the code in the README should be enough to understand what's going on. Alpha stuff here but I think the main things missing are weak pointers and a ref counted array. Given that I've never had to use std::weak_ptr in C++, I'm not in a hurry to implement the former.

Nice work!

Notable design decisions / features:

. The smart pointers are responsible for allocating the memory for the container object using the allocator of choice. This is to guarantee that one can't allocate and deallocate using different allocators.

Nice!

. The allocator has to be specified as part of the type: this means the user can choose how to store it in the smart pointer, which for singletons (e.g. Mallocator) or stateless allocators means they can take up zero space. If a singleton (or the default theAllocator), the allocator doesn't need to be passed in to the constructor, otherwise it does. Specifying, e.g. Mallocator also means the relevant code can be marked @nogc.

After extensively studying how C++ allocator framework works, I got to the notion that making the allocator part of the type is an antipattern.

I was aware of this, but here we have a crucial workaround - theAllocator, which is the default anyway. It's probably the best of both worlds, since you can still specify the type if needed, which also means the guarantee of @nogc if needed.


. RefCounted only increments/decrements the ref count atomically if the contained type is `shared`

Great. Can RefCounted itself be shared? I learned this is important for composition, i.e. you want to make a RefCounted a field in another object that is itself shared, immutable etc.

Since it has a destructor, no:

http://forum.dlang.org/post/sqazguejrcdtjimtj...@forum.dlang.org

The only way to do that would be to split it into two. Which I guess I could with a template mixin implementing the guts.


. RefCounted!(shared T) can be sent to other threads.

Awes.

. UniqueArray behaves nearly like a normal array. You can even append to it, but it won't use GC memory (unless, of course, you chose to use GCAllocator)!

This may be a great candidate for the standard library.

I think this needs to be used in production first, and having it as a dub package makes it easy for people to do so.


Atila

Reply via email to