user1478572
user1478572

Reputation: 11

How do you create a copy constructor of pointers to objects (deep copy)?

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

Answers (3)

Rafael Baptista
Rafael Baptista

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

Puppy
Puppy

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

user267885
user267885

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

Related Questions