Future of SafeRefCounted
Dukc
ajieskola at gmail.com
Thu Mar 6 21:14:57 UTC 2025
On Wednesday, 5 March 2025 at 22:04:24 UTC, Derek Fawcus wrote:
> On Tuesday, 25 February 2025 at 11:46:44 UTC, Dukc wrote:
>> If you don't recall, and if I understand it correctly DIP25 is
>> essentially DIP1000 limited only to `ref` and `return ref`.
>> `scope`/`return scope` rules for
>> pointers/slices/classes/struct/unions aren't included. It's
>> already the default in the current language.
>
> How does this compare with a similar mechanism in C#, which
> seems to have something akin to scoped pointers?
>
> See the postscript in the below article, where this was added
> as a means of working around limits in C#'s existing "borrow
> checking", and preventing escapes.
>
> https://em-tg.github.io/csborrow/
DIP25 is pretty similar to this, except it can also specify
non-returning references.
DIP1000 is more advanced, though. It works not only with
`ref`erences, but also with pointers, arrays, structs and so on.
Meaning you can pass a slice of a static array on the stack to a
function, and it will be checked for escaping just like a `ref`
parameter would. DIP25 can't do that, and I think the C#
equivalent neither can.
Another thing DIP1000 enables over DIP25 is a `ref`erence to a
scoped pointer (or slice, or struct, or class), meaning you can
have a function that mutates a pointer to a local variable _in
place_ . From [my post in the official
blog](https://dlang.org/blog/2022/10/08/dip1000-memory-safety-in-a-modern-systems-programming-language-part-2/):
```D
@safe ref Exception nullify(return ref scope Exception obj)
{
obj = null;
return obj;
}
@safe unittest
{
scope obj = new Exception("Error!");
assert(obj.msg == "Error!");
obj.nullify;
assert(obj is null);
// Since nullify returns by ref, we can assign
// to it's return value.
obj.nullify = new Exception("Fail!");
assert(obj.msg == "Fail!");
}
```
. The exception `obj` points to in the unit test is allocated on
the stack because of `scope`, yet `nullify` can mutate the class
reference in place (as opposed to only the class itself). You
can't do this safely with DIP25 alone, since you can't have a
`ref` to another `ref`.
More information about the Digitalmars-d
mailing list