Reputation: 11
How do you create deep copy of dynamic array of pointers to objects? I believe in this code, I'm only allocating new memory for the pointers to objects, but they still pointed on the same location. Therefore, when I change the "copied" image, the original image is also changed, and vice versa.
Thanks!
declatration:
Class Scene
{
public:
.
.
.
.
private:
Image ** sceneImage;
int * coordinateX;
int * coordinateY;
int inputMax;
};
in copy constructor...
Scene::Scene (const Scene & source)
{
inputMax = source.inputMax;
sceneImage = new Image*[inputMax];
coordinateX = new int[inputMax];
coordinateY = new int[inputMax];
// copy even null indexes, because you can put images on null indexes
for (int i = 0; i < inputMax; i++)
{
sceneImage[i] = source.SceneImage[i];
coordinateX[i] = source.coordinateX[i];
coordinateY[i] = source.coordinateY[i];
}
}
Upvotes: 1
Views: 572
Reputation: 11499
Vectors is a good idea. But if you can't refactor all the code to use them:
for (int i = 0; i < inputMax; i++)
{
sceneImage[i] = new Image( *(source.SceneImage[i] ));
coordinateX[i] = source.coordinateX[i];
coordinateY[i] = source.coordinateY[i];
}
You will need to delete those images later.
Upvotes: 1
Reputation: 146910
Drop all uses of new[]
immediately. Use std::vector
. Then it will copy itself for you. And in addition, drop all uses of owning pointers and use smart pointers.
Upvotes: 4
Reputation:
I suggest you rather use vectors for this. They are more elegant for dynamic arrays than pointers and will be automatically copied.
Use naked pointers only when it makes semantic sense (array≠pointer). This will only rarely be the case in C++.
Upvotes: 2