C++ - 删除作为参数传递的数组
C++ - Deleting array passed as parameter
我在使用此功能时出现意外行为:
void myClass1::expandArray(myClass2 *arr, int newSize) //myClass1 is friend of myClass2
{
myClass2 *temp = new myClass2[newSize];
/*fill temp with data*/
delete[] arr;
arr = temp;
capacity = newSize; //capacity is a data member of the class
}
这个函数一开始执行正确,然后(这是我最困惑的地方)在第二次或第三次调用时,它只是冻结,完全没有反馈直到几分钟后程序崩溃。
我有一个版本,其中数组是 class 的私有成员,它没有作为参数传递,但它正常工作。
最新的编辑问题已经很清楚了。函数删除原始数组,然后复制一个本地指针——不以任何方式影响原始指针。结果,它一直指向(现已删除)原始数组。
示例:
int* my_arr = new int[10];
expandArray(my_arr, 25);
my_arr[0] = 5; // crash-boom-bang! my_arr still points to the same memory as it did before expandArray was called!
解决方案-正如我在评论中所说,使用std::vector
。将为您处理所有必要的调整大小。
如果您执意使用 C 风格的动态数组,您应该通过引用传递指针,即
void expandArray(MyClass*& arr, size_t sz);
我在使用此功能时出现意外行为:
void myClass1::expandArray(myClass2 *arr, int newSize) //myClass1 is friend of myClass2
{
myClass2 *temp = new myClass2[newSize];
/*fill temp with data*/
delete[] arr;
arr = temp;
capacity = newSize; //capacity is a data member of the class
}
这个函数一开始执行正确,然后(这是我最困惑的地方)在第二次或第三次调用时,它只是冻结,完全没有反馈直到几分钟后程序崩溃。
我有一个版本,其中数组是 class 的私有成员,它没有作为参数传递,但它正常工作。
最新的编辑问题已经很清楚了。函数删除原始数组,然后复制一个本地指针——不以任何方式影响原始指针。结果,它一直指向(现已删除)原始数组。
示例:
int* my_arr = new int[10];
expandArray(my_arr, 25);
my_arr[0] = 5; // crash-boom-bang! my_arr still points to the same memory as it did before expandArray was called!
解决方案-正如我在评论中所说,使用std::vector
。将为您处理所有必要的调整大小。
如果您执意使用 C 风格的动态数组,您应该通过引用传递指针,即
void expandArray(MyClass*& arr, size_t sz);