Challenge: write a reference counted slice that works as much as possible like a built-in slice

Stanislav Blinov stanislav.blinov at gmail.com
Tue Nov 9 19:57:21 UTC 2021


On Tuesday, 9 November 2021 at 18:16:03 UTC, H. S. Teoh wrote:

> I think Atila's point is that *by default* you should be able 
> to write high-level D code without needing to call malloc/free, 
> but when necessary, you can do so *and* still take advantage of 
> the high-level abstractions of the language (e.g., maintain 
> @safe-ty, etc.).

Oh, I understand the sentiment, I really do. That we need more 
out-of-the-box tried and true robust containers is not in 
question - hence the premise of this very topic by Andrei. It's 
this constant desire to "abstract away" the very things that you 
literally *need* to operate on that puzzles me. Hey, raw pointers 
are bad, don't use! Hey, "new" is bad, don't call! Well if you're 
not using raw pointers and you aren't calling "new", there's 
Python. Or something. You don't get to keep the performance, and 
power, of low level languages, if you desperately abstract 
everything away. "Zero-cost" abstractions aren't a thing, it's a 
buzzword myth.

>
>> It's the calling of such APIs that must be made @safe.
> [...]
>
> IMO, that's not possible. In general code that calls 
> malloc/free it's not possible to prove anything @safe. The only 
> way you can do this in a waterproof way is to implement the 
> equivalent of GC tracing at *compile-time* so that every call 
> to free() can be proven to happen exactly once for every call 
> to malloc(). This is obviously impossible.

Could be possible for allocators that don't need a free() for 
every malloc(). At least, I think it could be:

while (true)
{
     auto a = alloc.allocate(1);
     auto b = alloc.allocate(100500);
     // ...

     // if here you can prove that nothing escaped, the call is 
safe.
     // which means `allocate` needs to paint the result somehow.
     alloc.freeAll();
}

Yip, that is, effectively, manual GC.

> In general, it's a mistake to mark malloc/free as @safe or 
> pure, it's the wrong semantics and will only lead to trouble 
> down the road.

But if you can express ownership in the language, it should be 
possible to make at least a @safe interface to them.



More information about the Digitalmars-d mailing list