So say I have
foo* fooObject1 = new foo[10];
// here would go code for initializing fooObject1[0] to fooObject1[9] with a foo object for each.
foo* fooObject2 = new foo[30];
for(int = 0; i < 10; i++)
fooObject2[i] = fooObject1[i];
if(fooObject1 != NULL)
delete[] fooObject1; //this "destroys" the array, BUT ALSO calls the destructors of all the foo objects inside fooObject1, causing fooObject2 elements to be anything but what it was before.
fooObject1 = fooObject2;
where foo is a specific object created by me with its respective methods.
My problem here, however, is that I want to destroy the array that fooObject1 points to, but not the elements of the array, is there a way for that to be done in C++? I know another way to go around the problem is to overload the = (equals) operator, but in the program I need it for, writing that would include overloading many other = operators for many other classes, which makes it a tedious and long process.
I was hoping that in some way I could keep the objects in fooObject2, but get rid of the array pointed by fooObject1. So can this be done? How? If not how, then are there are websites you could redirect me to read about it?
These are independent. Your fooObject2 array has been allocated just as fooObject1 was, and assignment operators fired for each all along the way. you effectively have a copy of each object from fooObject1 in fooObject2.
you cannot abandon fooObject1. You need to delete[] it or you’ll leak memory. fooObject2, as written, is independent unless you have internal pointers in the fooObject class and a shallow copy was performed because you didn’t follow the Rule of Three.
The last line of this sets fooObject1 (the pointer) to point to the same objects as fooObject2 after you cleaned up fooObject1 and deleted its prior memory allocation, just FYI, but do NOT delete them BOTH after that reference is made; only delete ONE.