问题描述
你好,我正在研究我的字符串类,我想添加一个擦除功能。所以我想我采用的策略是在开始索引之前复制内存,然后在长度 + 开始索引之后复制内存。这只会复制要删除的部分之外的数据。
这是我的代码。
//size is the current size of the string not including the null terminator character
//data is the character array of data
void erase(const size_t start,const size_t length) {
if (start + length <= size) {
size_t tempsize = start + length;
char* temp = new char[size + 1 - length];
//copy before start
if(start > 0)
memcpy(temp,data,start);
//copy after start (including null terminator character)
memcpy(temp + start,data + start + length,size + 1 - length - start);
delete[] data;
data = temp;
data[size] = '\0';
size = tempsize;
}
}
通过删除您想要的字符数量,它完全可以正常工作,但是当我删除字符串时它会引发堆损坏错误。
解决方法
我不知道为什么,但它停止抛出异常,如果需要,这里是当前代码。
void erase(const size_t& start,size_t length) {
if (start >= size) {
return;
}
if (start + length > size) {
length = size - start;
}
char* temp = new char[size + 1 - length];
//copy before start
if (start > 0)
memcpy(temp,data,start);
//copy after start (including null terminator character)
memcpy(temp + start,data + start + length,size + 1 - length - start);
delete[] data;
data = temp;
size = size - length;
}