DIP77 - Fix unsafe RC pass by 'ref'

Michel Fortin via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 10 14:50:13 PDT 2015


On 2015-04-10 21:29:19 +0000, Walter Bright <newshound2 at digitalmars.com> said:

> On 4/10/2015 2:11 PM, Martin Nowak wrote:
>> On 04/09/2015 01:10 AM, Walter Bright wrote:
>>> http://wiki.dlang.org/DIP77
>> 
>> In the first problem example:
>> 
>>   struct S {
>>       RCArray!T array;
>>   }
>>   void main() {
>>       auto s = S(RCArray!T([T()])); // s.array's refcount is now 1
>>       foo(s, s.array[0]);           // pass by ref
>>   }
>>   void foo(ref S s, ref T t) {
>>       s.array = RCArray!T([]);      // drop the old s.array
>>       t.doSomething();              // oops, t is gone
>>   }
>> 
>> What do you do to pin s.array?
>> 
>> auto tmp = s;
>> 
>> or
>> 
>> auto tmp = s.array;
>> 
> 
> The latter.

And how is it pinned in this case?

  struct S {
      private RCArray!T array;
      ref T opIndex(int index) return { return array[index]; }
      void clear() { s.array = RCArray!T([]); }
  }
  void main() {
      auto s = S(RCArray!T([T()])); // s.array's refcount is now 1
      foo(s, s[0]);           // pass by ref
  }
  void foo(ref S s, ref T t) {
      s.clear();            // drop the old s.array
      t.doSomething();              // oops, t is gone
  }

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list