开发者

Passing multidimensional array back through access members

I have a class "foo" that has a multi dimensional array and need to provide a copy of the array through a getArray member. Is there a nice way of doing this when the array is dynamically created so I can not pass the array back a const as the array is always being deleted, recreated etc. I thought about creating a new dynamic array to pass it back but is this acceptable as the calling code would need to know to开发者_高级运维 delete this etc.


Return an object, not a naked array. The object can have a copy constructor, destructor etc. which will do the copying, deletion etc. for the user.

class Matrix {
   // handle creation and access to your multidim array
   // including copying, deletion etc.
};

class A {    // your class
   Matrix m;     // the classes matrix
   Matrix getArray() {
       return m;
   }
};


Easy answer to your question is, not this is not a good design, as it should be the creating class that should handle the deletion/release of the array.

The main point is why do you keep deleting/recreating this multi dimensional array? Can you not create one instance, and then just modify when need be?

Personally I would return the array as it is, and iterate over it and do any calculations/functions on it during the loop therefore saving resources by not creating/deleting the array.


Neil's probably the best answer. The second best will be not to use an array. In C++, when you talk about dynamic array, it means vector.

There are two possibilities:

  1. nested vectors: std::vector<int, std::vector<int> >(10, std::vector<int>(20))
  2. simple vector: std::vector<int>(200)

Both will have 200 items. The first is clearly multi-dimensional, while the second leaves you the task of computing offsets.

The second ask for more work but is more performing memory-wise since a single big chunk is allocated instead of one small chunks pointing to ten medium ones...

But as Neil said, a proper class of your own to define the exact set of operations is better :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜