pointer stuff...again

Started by
1 comment, last by RZ 22 years, 6 months ago
Hi I have a class like this: class A { public: int *num; public: A(){num = new int[1];} ~A(){if(num){delete[] num;}} }; And a little funktion: A* func(int &size) { size = 1; A *a; a = new A[size]; a[0].num[0] = 99; return a; } And a little program: int main() { int size; A *a,*a_tmp; a_tmp = new A[100]; a_tmp = func(size); a = new A[size]; memcpy(a,a_tmp,sizeof(A)*size); delete[] a_tmp; } This is just an example..as u can see its not very useful. The thing is am trying to clean up the memoryleaks in my program and I cant figure out how I can do this in a nice way... If I delete the temp pointer in this example I lose all data in pointer "a" too. So the question is how can i copy the data in one pointer to another like in the example and then delete the first one. Edited by - RZ on October 21, 2001 5:43:22 PM
Advertisement
memcpy (and the compiler generated assignment operator) only creates a shallow copy of an object. This means that when you copy a_tmp[0] to a[0] the ''num''-pointers in both will point to the same memory location. You should create a deep copy. the easiest way is probably to define an assignment operator for your class, and avoid using memcpy to copy instances of it.

e.g. in the declaration of A you put something like:
  A& operator = (const A& a){   *num = *a.num; // num always points to 1 element in this example};  


then instead of memcpy(a, a_tmp, sizeof(A)*size) you would write something like:
  for (int i = 0; i < size; ++i){   a[i] = a_tmp[i];};  

This was a very simple example, and I probably forgot something. If you have a C++ book, look up ''operator overloading'' in it.
Thanks for the reply!

I was hoping that you could do this without for loops
but I guess i have to use them...

Edited by - RZ on October 21, 2001 8:06:21 PM

This topic is closed to new replies.

Advertisement