复制构造函数的C++辅助函数

C++ helper function for copy constructor

本文关键字:函数 C++ 构造函数 复制      更新时间:2023-10-16

我一直没能找到这个问题的好答案。

我正在开发一个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;
}

目前,它不起作用。我能看到的一个问题是,一旦复制函数结束,我就试图返回一个超出范围的变量。我以前尝试过返回一个引用,但编译器抛出了错误,这无论如何都无助于解决范围问题。

但我甚至不确定我的逻辑是否正确,也就是说,你能在构造函数中做这样的事情吗?或者我应该只是在复制构造函数和赋值运算符中显式地写出代码(而不实现helper方法copy(?

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

有一种更简单、更惯用的方法可以实现您想要的功能:复制和交换惯用方法。

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

话虽如此,我强烈建议您选择一本很好的C++入门书,它将涵盖正确实现复制构造函数和复制赋值运算符的基础知识。

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

重载赋值运算符将this的内容复制到接收的参数。对于copy,不需要返回任何东西或创建本地对象。只需从复制到即可。

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

三条规则应该有助于更好地了解这些。