复制构造函数的C++辅助函数
C++ helper function for copy 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;
}
目前,它不起作用。我能看到的一个问题是,一旦复制函数结束,我就试图返回一个超出范围的变量。我以前尝试过返回一个引用,但编译器抛出了错误,这无论如何都无助于解决范围问题。
但我甚至不确定我的逻辑是否正确,也就是说,你能在构造函数中做这样的事情吗?或者我应该只是在复制构造函数和赋值运算符中显式地写出代码(而不实现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
}
三条规则应该有助于更好地了解这些。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗