Creating a reference counted type?
ZombineDev via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 12 08:08:39 PDT 2016
On Sunday, 12 June 2016 at 14:49:18 UTC, Gary Willoughby wrote:
> On Sunday, 12 June 2016 at 14:45:12 UTC, ketmar wrote:
>> ahem... wut?! we have one copy of our struct freed half the
>> way, and another copy has refcount of 2, so it won't be freed
>> at all. it doesn't so innocent as it looks: we may try to use
>> `f` in `main`... just to find out that resources was
>> mysteriously freed, and refcount is total garbage.
>
> Hmmm. I thought it looked *too* simple. Have you any idea if
> there is a simple solution to this?
You need to allocate the ref count on the heap so it is actually
shared between all copies of the struct. Also if you want to
share the reference between multiple threads, you need to use
core.atomic.atomicOp for incrementing and decrementing.
See std.typecons.RefCounteed's implementation for reference
https://github.com/dlang/phobos/blob/v2.071.0/std/typecons.d#L4712
You can use AffixAllocator
http://dlang.org/phobos-prerelease/std_experimental_allocator_building_blocks_affix_allocator.html, so that ref count is automatically placed before or after the actual objected that is being ref counted. Just note that AffixAllocator is safe to use only by a single thread.
More information about the Digitalmars-d-learn
mailing list