首页 > 解决方案 > 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 个限制。据我了解,我必须删除它,因为数组无法调整大小,然后复制新的大小(连同值)。

任何帮助将不胜感激,并提前感谢您。另外,如果需要更多代码,请见谅。我不想给超出需要的东西。

标签: c++arraysdynamic-arraysdelete-operator

解决方案


您的赋值运算符实现不正确。它movieArray在分配新数组之前释放temp数组。如果分配失败,则该类将处于不良状态。而且您没有在调用之前将temp数组分配给(永远不会到达,编译器应该警告您)。movieArrayreturn *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;
}

推荐阅读