Enhancements can enable memory-safe reference counting

workman workman at gmail.com
Fri Nov 26 06:58:32 UTC 2021


On Friday, 26 November 2021 at 04:37:16 UTC, tsbockman wrote:
>
> The hackish, possibly fragile nature of the workaround, and the 
> [destructor 
> issue](https://issues.dlang.org/show_bug.cgi?id=21981) still 
> make my solution unsuitable for the standard library for now, 
> though.


I have a runtime solution for borrow check, share it here.



```d

struct Obj {
      size_t version;
      size_t counter;
}

struct Ptr {
         Obj* obj;
         size_t ver;
         alias this self;
         @property ref self() return scope  {
            // check ver first
            assert(ver is obj.ver);
            return *obj;
         }
}

```


To make this work the obj memory can not released before all 
Pointer released,  but it can be reused for new instance, so a 
memory pool is used to manage every struct|class.


You need update version when object destroyed by counter.

You can make sure there is only one mut borrow for a object like 
RUST.

You can make WeakRef that don`t change counter, but become 
Option<Null> when the object released.

You can make Unique ownership with this like RUST, but with 
WeakRef immutable pointer.


Almost every things I want for RUST can be done from runtime, the 
price is managed memory pool for every object you want this kind 
behavior.

I use it for 3 years with my private betterC framework, It also 
can work cross thread with Atomic counter and version.

I give up on class and exception, use c library if there 
available. I use mecca swichInto Fiber with betterC, but can be 
graceful exit(mecca fiber never exit).

With libuv I build cross platform app for 
Andoird/IOS/Windows/Mac/Linux.

The binary is very small compare to C++.


The price is manage memory pool for your self for each diff kind 
object. This object pool can be reused without fully destroyed.  
(a methed call reset before return to pool)




More information about the Digitalmars-d mailing list