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

Paul Backus snarwin at gmail.com
Tue Dec 14 17:11:10 UTC 2021


On Tuesday, 14 December 2021 at 16:45:20 UTC, Stanislav Blinov 
wrote:
> On Tuesday, 14 December 2021 at 16:17:30 UTC, user1234 wrote:
>>
>> There no issue there, `this` not used at all. Segfaults will 
>> start to happen, as expected, when trying to access a member 
>> variable.
>
> No, they wouldn't, per current spec.
>
> https://dlang.org/spec/declaration.html#void_init
> https://dlang.org/spec/function.html#safe-functions
>
> Per that, this is @safe:
>
> ```d
> import core.sys.linux.fcntl;
> import core.sys.linux.unistd;
>
> struct MMap
> {
>     private int fd;
>     @disable this();
>     @disable this(this);
>     // ...
>     ~this() @trusted {
>         if (isValid) {
>             auto msg = "closed";
>             size_t len = msg.length;
>             write(fd, &len, len.sizeof);
>             write(fd, msg.ptr, len);
>             close(fd);
>         }
>     }
>
>     private bool isValid() const @trusted {
>         import core.stdc.errno;
>         return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
>     }
> }
>
> void main() @safe
> {
>     // ...
>     MMap mm = void; // currently allowed because MMap doesn't 
> contain indirections
>     // ...
>
> } // nothing may happen, or may crash, or may write into 
> someone else's memory, or to stdout...
> ```
>
> Prolly should make an enhancement request for spec of @safe to 
> disallow void initialization altogether.

This is one of the problems that [DIP 0135 (`@system` 
variables)][1] aims to solve. Specifically, it is the same class 
of problem described in [the `ShortString` example][2], where 
memory safety relies on the integrity of non-pointer data.

[1]: https://github.com/dlang/DIPs/blob/master/DIPs/DIP1035.md
[2]: 
https://github.com/dlang/DIPs/blob/master/DIPs/DIP1035.md#example-short-string


More information about the Digitalmars-d mailing list