用于复制构造函数的C ++帮助函数

时间:2011-09-08 04:39:18

标签: c++ pointers constructor

我无法找到这个问题的好答案。

我正在研究一个C ++程序,我正在尝试实现一个名为 copy 的函数,该函数将另一个对象的引用作为参数。然后,它返回此对象的深层副本。

我项目的一些背景知识: Scene 类包含指向NULL或 Image 类的实例的指针的动态数组(称为“Images”),这里没有显示 - 但它可以正常工作(它从第三方库EasyBMP继承了它的所有方法)

我这样做的原因是为了避免在两个地方重复代码,但我很可能采取了错误的方法。

我在赋值运算符中调用此函数:

Scene const & Scene::operator=(Scene const & source)
{
    if (this != &source) {
        clear();
        copy(source);
    }
    return *this;
}

我的副本构造函数:

Scene::Scene(Scene const & source)
{
    copy(source);
}

最后,我的copy()方法如下所示:

Scene const & Scene::copy(Scene const & source)
{
    Scene res(source.Max);
    for (int i=0; i<res.Max; i++)
    {
        delete res.Images[i];
        if (source.Images[i] != NULL) 
            res.Images[i] = new Image(*(source.Images[i]));
        else
            res.Images[i] = NULL;
    }   

    return res;
}

目前,它不起作用。我可以看到的一个问题是,我试图在复制功能结束后立即返回超出范围的变量。我之前尝试过返回一个引用,但是编译器抛出错误,这无论如何都无助于范围问题。

但是我甚至不确定我的逻辑是否正确,即你甚至可以在构造函数中做这样的事情吗?或者我应该只是在复制构造函数和赋值运算符中明确写出代码(不实现辅助方法 copy )?

我对C ++和指针都很陌生,所以任何指导都会非常感激。

2 个答案:

答案 0 :(得分:3)

有一种更轻松,更惯用的方式来做你想做的事:the copy-and-swap idiom

// N.B. Not tested, but shows the basic structure of the copy-and-swap idiom.
class Scene
{
public:
    Scene(int)
    {
        // Initialize a pointer array of Images
    }

    ~Scene()
    {
        // Get rid of our pointer array of Images
    }

    // Copy constructor
    // N.B. Not exception safe!
    Scene(const Scene& rhs) : imgPtrArray(new Image*[rhs.max])
    {
        // Perform deep copy of rhs
        for (int i=0; i < rhs.max; ++i)
        {
            if (rhs.imgPtrArray[i] != 0)    
                imgPtrArray[i] = new Image(*(rhs.imgPtrArray[i]));
            else   
                imgPtrArray[i] = 0;   
        }      
    }

    // Copy assignment constructor
    // When this is called, a temporary copy of Scene called rhs will be made.
    // The above copy constructor will then be called. We then swap the
    // members so that this Scene will have the copy and the temporary
    // will destroy what we had.
    Scene& operator=(Scene rhs)
    {
        swap(rhs);
        return *this;
    }

    void swap(Scene& rhs)
    {
        // You can also use std::swap() on imgPtrArray
        // and max.
        Images** temp = imgPtrArray;
        imgPtrArray = rhs.imgPtrArray;
        rhs.imgPtrArray = temp;
        int maxTemp = max;
        max = rhs.max;
        rhs.max = maxTemp;
    }

private:
    Images** imgPtrArray;
    int max;
};

话虽如此,我强烈建议你pick up a good introductory C++ book,它将涵盖正确实现复制构造函数和复制赋值运算符的基础知识。

答案 1 :(得分:0)

Scene const & Scene::operator=(Scene const & source);

重载的赋值运算符将的内容复制到收到的参数。对于copy,不需要返回任何内容或创建本地对象。只需将会员明智的副本从复制到来源即可。

 void Scene::copy(Scene const & source){
     // Member wise copy from this to source
 }

Rule of three应该有助于更好地了解这些内容。