【发布时间】:2021-02-14 18:00:42
【问题描述】:
我们可以更改由new 运算符创建的数组的大小,就像使用reallocate() 完成的调整大小一样,如下所示?
在 C 中:
int *p = (int*)malloc(size_of(int));
reallocate(p,2*size_of(int));
如果不能,如何改变new操作符创建的数组的大小?
【问题讨论】:
-
不,这是不可能的。在 C++ 中,
std::vector应该用于此目的。它在后台管理重新分配。 -
有时
std::vector的再发明是学习练习的重点。虽然 STL 很好,应该继续使用,但有超过 2 年的遗留代码使用各种new和delete重新分配方案。查看类似问题First attempt at using new to dynamically create struct array, program hangs without error -
要重新分配的 C 函数名为
realloc,而不是reallocate。