RCArray is unsafe

Manu via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 3 00:04:08 PST 2015

On 3 March 2015 at 06:37, Walter Bright via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> On 3/1/2015 12:51 PM, Michel Fortin wrote:
>> That's actually not enough. You'll have to block access to global
>> variables too:
>>      S s;
>>      void main() {
>>          s.array = RCArray!T([T()]);   // s.array's refcount is now 1
>>          foo(s.array[0]);           // pass by ref
>>      }
>>      void foo(ref T t) {
>>          s.array = RCArray!T([]);      // drop the old s.array
>>          t.doSomething();              // oops, t is gone
>>      }
> Thinking about it, there are many other ways this can happen. At the moment,
> I'm stuck thinking of a solution other than requiring foo() to be pure.
> Anyone have ideas?

My immediate impression on this problem:

s.array[0] is being passed to foo from main. s does not belong to main
(is global), and main does not hold have a reference to s.array.
Shouldn't main just need to inc/dec array around the call to foo when
passing un-owned references down the call tree.
It seems to me that there always needs to be a reference _somewhere_
on the stack for anything being passed down the call tree (unless the
function is pure). Seems simplest to capture a stack ref at the top
level, then as it's received as arguments to each callee, it's
effectively owned by those functions and they don't need to worry

So, passing global x to some function; inc/dec x around the function
call that it's passed to...? Then the stack has its own reference, and
the global reference can go away safely.

More information about the Digitalmars-d mailing list