RCArray is unsafe
weaselcat via Digitalmars-d
digitalmars-d at puremagic.com
Mon Mar 2 21:58:47 PST 2015
On Tuesday, 3 March 2015 at 05:40:59 UTC, Walter Bright wrote:
> On 3/2/2015 9:27 PM, deadalnix wrote:
>> On Tuesday, 3 March 2015 at 01:56:09 UTC, Walter Bright wrote:
>>> On 3/2/2015 4:40 PM, deadalnix wrote:
>>>> After moving resources, the previous owner can no longer be
>>>> used.
>>>
>>> How does that work with the example presented by Marc?
>>
>> I'm not sure what you don't understand. The comment in the
>> sample code seems
>> clear to me.
>>
>> // "Move" `a` into `b`
>> // Here's what happens under the hood: the pointer `a` gets
>> copied (*not*
>> // the data on the heap, just its address) into `b`. Now both
>> are pointers
>> // to the *same* heap allocated data. But now, `b` *owns* the
>> heap
>> // allocated data; `b` is now in charge of freeing the memory
>> in the heap.
>> let b = a;
>>
>> Now you have a variable b that owns the data. a is not usable
>> anymore.
>>
>> // After the previous move, `a` can no longer be used
>> // Error! `a` can no longer access the data, because it no
>> longer owns the
>> // heap memory
>> //println!("a contains: {}", a);
>> // TODO ^ Try uncommenting this line
>>
>> As explained here, if a is used, this is an error.
>>
>> In the example a is move to b. If you had let b = &a, then b
>> would borrow from
>> a. The same way, a would not be usable anymore. The difference
>> with move is
>> that, when b is destroyed, in the first case memory is freed.
>> in the second
>> case, memory is not freed and a is "reenabled".
>>
>> It is either possible to borrow once and disable who you
>> borrow from, or borrow
>> multiple time and everything become immutable for the time you
>> borrow.
>>
>> This makes the problems mentioned in this thread effectively
>> impossible happen.
>
> What if 'a' is a field of a struct in some non-trivial data
> structure? How is the compiler going to statically keep track
> of which field instances in this structure are not usable?
Borrowing 'a' from a struct would make the parent struct
immutable during the borrow scope of 'a', I believe.
More information about the Digitalmars-d
mailing list