2

I have a COWarray that works OK, but now I want to expand the number of dimensions like so:

type
  TCOWArray2<T> = record
  private
    type
      TItem = record
        fItems: TArray<T>;
        fStart, fFinish: NativeInt;
      end;
  private
    fItems: array of TItem;
  private
     methods
  public
     ....
  end;

The array splits up its items in blocks. Every sub array has e.g. 100 items and the mean array has however many items are needed.
To the outside only a one dimensional array is presented, but internally the data of type T is stored in the subarray.

This way I can have copy of write with very little copying going on when a single item changes. Instead of cloning all 20,000 items, only 100 items are clones plus the mean array with 200 items, i.e. only 300 items a nearly 99% reduction of effort and storage.

The problem is that I need to keep track of changes in the reference count of the main array and propagate those to the sub-arrays.

Something like:

procedure TCOWArray<T>.SomeMember.AddRef;
var
  Item: TItem;
begin
  inherited;
  for Item in fItems do Item.IncreaseRefCount;
end;

Obviously for performance reasons I will use a plain for i loop

How do I do this?
I was thinking of adding a custom TInterfaced Object, but I'm not sure how to make it work.

4

1 回答 1

4

这似乎是多维系列问题中的第二个。

该系列的第一个问题,外部维度,在这里:为什么编译器坚持我的函数不是内联的?尽管问题标题涉及错误消息,但它最终变成了关于实现写入时复制数组的问题。那是问题的一维版本。

现在我们继续讨论这个问题。这是二维版本。我们以与第一个问题相同的方式解决它。因为它实际上是完全相同的问题。一旦我们可以解决一维数组的问题,同样的解决方案也适用于 N 维数组。

当您需要修改数组的元素时,请调用SetLength您的内部数组。这为您提供了一个独特的外部数组。此处发生的任何复制仅复制对内部子数组的引用。

然后确定您需要操作的内部子数组。完成后,SetLength再次调用以使该内部子数组唯一。然后修改值。

添加多少维度并不重要。答案总是一样的。我希望这个问题可以终止这个系列!;-)

于 2014-06-20T21:45:23.000 回答