c++ - C++ 通过赋值运算符深拷贝动态数组
问题描述
我正在尝试将动态分配的数组复制到实例中。我的代码似乎正在复制这些值,但它还需要调整数组的大小以匹配“&other”大小的数组。
关于代码的一些信息:手头有两个类,一个是“电影”,它以标题、电影时间和导演(所有指针)作为私有成员。还有另一个称为“MovieCollection”,它是一个数组,将“Movie”的每个实例存储在给定的索引中。
//These are private member variables:`
int ArrySize = 50; //There is another section of code that points to this and resizes if needed, I believe it needed a size at runtime though.
//Array to store instance of "movie"
Movie *movieArry = new Movie[ArrySize];
//This is assignment operator
const MovieCollection& operator=(const MovieCollection& other)
{
delete []movieArray;
int otherSizeArry = other.ArrySize;
Movie* temp;
temp = new Movie[otherSizeArry];
for (int i = 0; i < otherSizeArry; i++)
temp[i] = other.movieArry[i];
return *this;
delete []temp;
}
在创建实例时,我使用了我编写的另一个函数来调整数组的大小。例如,我要复制的实例有 10 个索引,但我尝试将值复制到的新实例仍然有 50 个限制。据我了解,我必须删除它,因为数组无法调整大小,然后复制新的大小(连同值)。
任何帮助将不胜感激,并提前感谢您。另外,如果需要更多代码,请见谅。我不想给超出需要的东西。
解决方案
您的赋值运算符实现不正确。它movieArray
在分配新数组之前释放temp
数组。如果分配失败,则该类将处于不良状态。而且您没有在调用之前将temp
数组分配给(永远不会到达,编译器应该警告您)。movieArray
return *this;
delete []temp
运算符应该看起来更像这样:
MovieCollection& operator=(const MovieCollection& other)
{
if (&other != this)
{
int otherSizeArry = other.ArrySize;
Movie* temp = new Movie[otherSizeArry];
for (int i = 0; i < otherSizeArry; ++i) {
temp[i] = other.movieArry[i];
}
// alternatively:
// std::copy(other.movieArry, other.movieArry + otherSizeArry, temp);
std::swap(movieArray, temp);
ArrySize = otherSizeArry;
delete[] temp;
}
return *this;
}
如果你的类有一个复制构造函数(它应该——如果没有,你需要添加一个),赋值运算符的实现可以大大简化:
/*
MovieCollection(const MovieCollection& other)
{
ArrySize = other.ArrySize;
movieArray = new Movie[ArrySize];
for (int i = 0; i < ArrySize; ++i) {
movieArray[i] = other.movieArry[i];
}
// alternatively:
// std::copy(other.movieArry, other.movieArry + ArrySize, movieArray);
}
*/
MovieCollection& operator=(const MovieCollection& other)
{
if (&other != this)
{
MovieCollection temp(other);
std::swap(movieArray, temp.movieArray);
std::swap(ArrySize, temp.ArrySize);
}
return *this;
}
推荐阅读
- javascript - 如何使用下拉列表从 json 文件中选择类别
- python - 如何在网络上提供 PDF 文件?
- javascript - 在 Angular 6 中使用 ngFor 循环动态创建输入元素数组并添加基于模板引用变量的动态验证
- javascript - gmail 插件检测是否正在使用移动设备
- bigchaindb - 了解 BigchainDB 中交易的状态
- excel - Excel VBA函数循环范围并测量多个相关性
- python - 谷歌多巴胺
- c# - C# 配置文件的加密密码
- java - java中的UUID制作int
- django - 如何创建具有可变数量字段的 Django 表单