【问题标题】:How do you create a copy constructor of pointers to objects (deep copy)?如何创建指向对象的指针的复制构造函数(深拷贝)?
【发布时间】:2013-04-04 04:26:48
【问题描述】:

如何创建指向对象的动态指针数组的深层副本?我相信这段代码,我只是为指向对象的指针分配新内存,但它们仍然指向同一个位置。因此,当我更改“复制”的图像时,原始图像也会更改,反之亦然。

谢谢!

声明:

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];
    }
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    立即放弃所有new[] 的使用。使用std::vector。然后它会为你复制自己。此外,放弃所有使用拥有指针并使用智能指针。

    【讨论】:

      【解决方案2】:

      我建议您为此使用向量。对于动态数组,它们比指针更优雅,并且会被自动复制。

      只有在语义上有意义时才使用裸指针(数组≠指针)。在 C++ 中这种情况很少见。

      【讨论】:

        【解决方案3】:

        向量是个好主意。但是如果你不能重构所有的代码来使用它们:

        for (int i = 0; i < inputMax; i++)
        {
            sceneImage[i] = new Image( *(source.SceneImage[i] ));
            coordinateX[i] = source.coordinateX[i];
            coordinateY[i] = source.coordinateY[i];
        }
        

        您需要稍后删除这些图像。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-01
          • 2014-07-06
          • 2022-01-09
          • 1970-01-01
          相关资源
          最近更新 更多