Borrowing and Ownership
Sebastiaan Koppe
mail at skoppe.eu
Wed Nov 13 11:23:55 UTC 2019
On Wednesday, 13 November 2019 at 09:52:24 UTC, Timon Gehr wrote:
> On 13.11.19 09:08, Atila Neves wrote:
>> And how would the application of `scope` to, say, `int` affect
>> it? What would the compiler do with that?
>> ...
>
> The same things it would do with other types. You can't escape
> the value or make non-borrowed copies. It's unlikely to have
> useful applications for a plain integer, but you could have a
> `struct Handle{ private int handle; ... }` that carries the
> invariant that the handle is valid.
>
> Then you can do things like:
>
> void workWithHandle(scope Handle handle)@safe{ ... }
>
> void unsafe()@trusted{
> auto handle=getHandle();
> workWithHandle(handle);
> disposeHandle(handle);
> }
>
> If `scope` was restricted to pointers, you would have to pass
> pointers to handles in order to get any of that type checking.
> (IIRC, this complaint was on this newsgroup not too long ago.)
> In general, it would make the rules less useful for @trusted
> libraries that need to restrict access patterns from @safe code.
Yes, yes, yes.
It would happen anytime you refer to an external resource by
index that you need to release after use. (e.g. a DB cursor
index).
I currently use this strategy in spasm to release objects held on
the JS side. The object is released automatically whenever the
handle goes out of scope.
The benefit is that you don't have to do reference counting, but
you still can wrap it in one if you need to.
More information about the Digitalmars-d
mailing list