borrowed pointers vs ref
Walter Bright via Digitalmars-d
digitalmars-d at puremagic.com
Thu May 15 11:08:08 PDT 2014
On 5/15/2014 5:18 AM, Dicebot wrote:
> On Wednesday, 14 May 2014 at 19:03:20 UTC, Walter Bright wrote:
>> 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).
get() is returning a pointer to its internally managed data (in the form of []).
You're right that transitivity of borrowing would support this safely, but I am
not proposing that for ref. To make slicing Buffer safe, one would have to
overload opSlice and then manage access to the slice.
More information about the Digitalmars-d
mailing list