#include <cstdlib>
#include <cstring>
#include <string>
using std::string;
string *arr_ptr;
int capacity;
void add() {
int old_capacity = capacity;
capacity <<= 1;
// double the capacity
string *tmp_ptr = new string[capacity];
// apply new space
memmove(tmp_ptr, arr_ptr, sizeof(string) * old_capacity);
// copy
delete[] arr_ptr;
// free the original space
arr_ptr = tmp_ptr;
arr_ptr[capacity - 1] = "occupied";
// without this statement, everything "seems" to be fine.
}
int main() {
arr_ptr = new string[1];
capacity = 1;
for (int i = 0; i < 3; i++) add();
}
运行代码。正如你所看到的,当字符串的desctrutor被调用时,程序崩溃。尝试对delete
的行进行注释并再次检查。为什么我不能std :: string?
我怀疑std :: string会保留自己的一些地址信息。它在内存中的位置发生变化时不会被通知。
此外,由于memmove
并不总是按预期工作,在C++中复制类实例数组的适当表达式是什么?
使用'std :: vector'。 – chris
必须第二克里斯。不要将旧式风格的数组与老式风格的“新”(好的)stl容器/类混合使用。 – Najzero
@chris我正在为我的数据结构类写作业。 XD – Determinant