DIP 1021--Argument Ownership and Function Calls--Community Review Round 1

Nick Treleaven nick at geany.org
Thu Jul 18 10:42:15 UTC 2019


On Thursday, 18 July 2019 at 09:09:37 UTC, ag0aep6g wrote:
> ... because a function could call `clear` while already having 
> obtained `ptr`.

I think the DIP allows a destructor freeing ptr to be trusted:

import core.stdc.stdlib, std.stdio;

struct S
{
     private byte* ptr;
     import core.stdc.stdlib;

     // FIXME return scope doesn't seem to work (with -dip1000)
     byte* get() @safe return scope { return ptr; }
     this(byte value) @trusted
     {
         ptr = cast(byte*) calloc(1, 1);
         *ptr = value;
     }
     ~this() @trusted
     {
         free(ptr);
     }
}

@safe:

// won't compile with DIP 1021
void bad(ref S s, ref byte b)
{
     s.destroy;
     b++;
}

byte* f()
{
     auto s = S(5);
     bad(s, *s.get);
     return s.get; // this shouldn't compile, but it does
}

> Except it still wouldn't be 100% ok, because @safe code could 
> set `ptr = new byte;` and then `free` would be called on GC 
> memory.

It is @safe outside the module that S is defined in with a 
private ptr (modulo .tupleof).


More information about the Digitalmars-d mailing list