【发布时间】:2013-06-06 06:29:58
【问题描述】:
#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();
}
运行代码。如您所见,调用字符串的析构函数时程序崩溃。尝试评论delete这一行并再次查看。
我怀疑 std::string 会保留一些自身的地址信息。当它在内存中的位置发生变化时,它不会被通知。
此外,由于memmove 并不总是按预期工作,那么在 C++ 中复制类实例数组的适当表达是什么?
【问题讨论】:
-
必须第二个克里斯。不要将 char 样式的数组旧样式与“新”(好吧)stl 容器/类混合。
-
@chris 我正在为我的数据结构类写作业。 XD