RCArray is unsafe

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 1 08:32:25 PST 2015


On 3/1/15 7:44 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm at gmx.net>" wrote:
> Walter posted an example implementation of a reference counted array
> [1], that utilizes the features introduced in DIP25 [2]. Then, in the
> threads about reference counted objects, several people posted examples
> [3, 4] that broke the suggested optimization of eliding
> `opAddRef()`/`opRelease()` calls in certain situations.
>
> A weakness of the same kind affects DIP25, too. The core of the problem
> is borrowing (ref return as in DIP25), combined with manual (albeit
> hidden) memory management. An example to illustrate:
>
>      struct T {
>          void doSomething();
>      }
>      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
>      }

Thanks for pointing this out - it's a real problem. -- Andrei




More information about the Digitalmars-d mailing list