RCArray is unsafe

sclytrack via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 5 11:34:03 PST 2015


On Wednesday, 4 March 2015 at 08:56:20 UTC, Ivan Timokhin wrote:
> Excuse me if I miss something obvious, but:
>
>     void main()
>     {
>         auto arr = RCArray!int([0]);
>         foo(arr, arr[0]);
>     }
>
>     void foo(ref RCArray!int arr, ref int val)
>     {
>         {
>             auto copy = arr; //arr's (and copy's) reference 
> counts are both 2
>             arr = RCArray!int([]); // There is another owner, 
> so arr
>                                    // forgets about the old 
> payload
>         } // Last owner of the array ('copy') gets destroyed 
> and happily
>           // frees the payload.
>         val = 3; // Oops.
>     }
>



struct PileInfo		"Red" 	TOP of PILE
{
	int refCount;
	RCDataBlock * top;
	RCDataBlock * bottom;
}

struct RCDataBlock	"Blue"	
{
	PileInfo * pileInfo;
	RCDataBlock * next;
	Array * payload;	//Actual Data.
}

struct RCArray
{
	RCDataBlock * block;
}


RCArray a,b,c,d;	//all different piles

a = b;
b = c;
d = a;			//makes them one single pile.


What if you pile them up. Blue cubes which contain the data.
And a Red cube containing the reference count equal to
the sum of all references to the blue cube of the same pile.
Basically a pile of blue cubes with a red cube on top.



1) RCArray a,b,c,d;		//------------

[1]
  x <-a

[1]
  x <-b

[1]
  x <-c

[1]
  x <-d


2) a = b;	//------------

[2]
  x <-[old b1]
  x <-a,b

[1]
  x <-c

[1]
  x <-d

3) b = c;	//------------


[3]
  x <-b,c
  x <-[old b1]
  x <-a,[old b2]

[1]
  x <-d


4) d=a;		//------------

[4]
  x <-b,c
  x <-[old b1]
  x <-[old a1],[old b2]
  x <-d,a





More information about the Digitalmars-d mailing list