RCArray is unsafe

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 2 21:27:20 PST 2015

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 
// 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 

// 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.

More information about the Digitalmars-d mailing list