@safe ref counted pointer
Stanislav Blinov
stanislav.blinov at gmail.com
Thu Jan 13 07:25:24 UTC 2022
On Wednesday, 12 January 2022 at 21:17:13 UTC, vit wrote:
> Hello,
> I want implement @safe ref counted pointer (similar to
> std::shared_ptr).
> Problem is that access to managed data of ref counted pointer
> is inherently unsafe because ref counted pointer can be
> released (managed data is destroyed) and scope
> reference/pointer can be still on the stack:
> Example:
>
> ```d
>
> import std.typecons;
>
> scope rc = RefCounted!int(5);
>
> (scope ref int data){
> rc = RefCounted!int(42);
>
> data = -1; ///dangling reference!
> }(rc);
>
> ```
>
> It look like i must choose from 2 options:
>
> 1) Method which can release managed data or move ownership of
> managed data are @safe but methods accessing managed data must
> be @system.
>
> 2) Method which can release managed data or move ownership of
> managed data are @system but methods accessing managed data
> can be @safe
3) Leave `get()` `@system` and simply make a `@safe` caller:
```d
struct SharedPtr(T)
{
// ...
auto apply(Dg)(scope Dg dg)
if (is(typeof(dg(typeof(this).init.get))))
{
auto tmp = this; // borrow another reference
return dg(ref () @trusted { return get(); } ());
}
// ...
}
void main() @safe
{
scope rc = SharedPtr!int(5);
rc.apply((scope ref data) {
rc = SharedPtr!int(42);
data = -1; // ok
});
}
```
More information about the Digitalmars-d
mailing list