borrowed pointers vs ref

Dicebot via Digitalmars-d digitalmars-d at puremagic.com
Thu May 15 05:18:21 PDT 2014


On Wednesday, 14 May 2014 at 19:03:20 UTC, Walter Bright wrote:
>>>> Also A can only control escaping of any internal references 
>>>> only by completely
>>>> prohibiting access to it which is not good. You have no 
>>>> means to say "feel free
>>>> to use this reference as long as you don't keep it outside 
>>>> of current scope".
>>>> And you effectively say "make all your array members private 
>>>> to keep borrowing
>>>> guarantees".
>>>
>>> You can by only returning ref's.
>>
>> Also slices and pointers (or structs with pointers inside).
>
> The idea is that 'ref' are borrowed pointers, so if you're 
> returning pointers, the borrowed semantics do not apply.

Somewhat more extended example:

struct Buffer
{
     private byte[] data;

     this() { this.data = (cast(byte*)malloc(42))[0..42]; }
     ~this() { free(this.data.ptr); }

     byte[] get(size_t a, size_t b) { return this.data[a..b]; }
}

void foo(ref Buffer buff)
{
     // here be trouble
     static int[] slice = buff.get(10, 20);
}

void foo2()
{
     Buffer buff;
     foo(buff);
     // destructor gets called, foo now has pointer to freed memory
}

Transitivity of borrowing ensures that you can use any object as 
an argument for function that takes a borrowed pointer and no 
reference to its internals will persist. Whatever memory 
management model of object type is.

With such borrowing implementation this example code is also 
totally @safe in spirit (assignment to static var will result in 
compile-time error).


More information about the Digitalmars-d mailing list