views:

67

answers:

2

Greetings everyone. I'm in need of some experiance here as how to deal with dynamic arrays with Objects.

I've a class 'SA', consisting of several objects 'Obj1', 'Obj2' etc...

Within the class I have a dynamic array 'SA_Array' which I initialize in the following manner where size sets its length:

double * SA_Array;
SA_Array = new double [size];

Now I've been trying to use the '=' operator on the above objects to make copies of the array in each object. Unfortunatly I've realised that it only equalizes the pointer and hence if I modify the array in one object, all the object SA_Array's are modified the same... Essentially leaving me with only one copy on the array.

e.g. Obj1.SA_Array == Obj2.SA_Array...

Are there any good suggestions as to how to overcome this and achieve object specific copies of SA_Array?

+4  A: 

If the size is determined at runtime, easiest to use one is a vector

vector<double> SA_Array(size);

Now you can copy, swap, resize it and it will act accordingly. If you need a pointer to the begin, you can do that with &SA_Array[0]. If the size is determined and fixed at compile time, you can use boost::array

boost::array<double, size> SA_Array;

You can use it like an array, but can also copy it and do stuff like SA_Array.begin() like with the vector. If you need a pointer to the begin, you can do that with SA_Array.data() or &SA_Array[0].

There is the way using raw pointers too like you did, and copying it manually

double *SA_Array;
SA_Array = new double[size];

double *SA_Copy;
SA_Copy = new double[size];
std::copy(SA_Array, SA_Array + size, SA_Copy);

But it is cumbersome as you will need to remember to delete[] them, which a vector will do all for you.

Johannes Schaub - litb
A: 

Either use a standard library collection, such as std::vector<double>, or, in the rare case that you need to have raw arrays, you can write a copy constructor, taking care to ensure exception safety.

Pete Kirkham