如何创建指向对象的动态指针数组的深拷贝?我相信这段代码,我只是为指向对象的指针分配新内存,但它们仍然指向相同的位置。因此,当我更改“复制”的图像时,原始图像也会更改,反之亦然。
谢谢!
声明:
Class Scene
{
public:
.
.
.
.
private:
Image ** sceneImage;
int * coordinateX;
int * coordinateY;
int inputMax;
};
在复制构造函数中...
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];
}
}
最佳答案
立即停止使用 new[]
。使用 std::vector
。然后它会为你复制自己。此外,放弃所有使用拥有指针并使用智能指针。
关于c++ - 如何创建对象指针的复制构造函数(深复制)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11180874/