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

标签 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++ 和指针还很陌生,因此非常感谢任何指导。

最佳答案

有一种更简单、更惯用的方法来做你想做的事: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 ,其中将涵盖正确实现复制构造函数和复制赋值运算符的基础知识。

关于复制构造函数的 C++ 辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7343171/

相关文章:

c++ - 如何在 Linux 中优化构建

c++ - 在scanf中引用int

要传递给 C 函数的 Objective-C 选择器指针

C++ 函数指针数组错误

c++ - 如何在我的 C++ 项目中包含 SQLite DLL?

c++ - 如何从 boost::posix_time::ptime 获取自纪元时间以来的毫秒数

c - 访问连续内存位置时出现打印错误

VC2010 中的 C++0x 对等构造函数

c++ - C 数组 vs 指针 : array is considered as a variable, array+0 被认为是指针?

c++ - 构造函数中的临时非常量 istream 引用 (C++)