views:

57

answers:

3

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.

Thanks in advanced

+3  A: 

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;
   }
};
anon
Not following 100% do you mind expanding?
A: 

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.

LnDCobra
A: 

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 :)

Matthieu M.