我做了两个字符串类的对象,每个对象都有char *指针。通过浅拷贝,我已经通过浅拷贝将第一个对象拷贝到第二个对象中。现在他们都指着同一个地方。浅拷贝后追加字符指针
我要做的就是通过一个对象附加char指针,以便它不会使另一个对象增加原始字符指针的大小,因此第二个对象指向相同的位置。
void String::append(char c) {
auto_ptr<StringBuffer> newdata(new StringBuffer);
newdata.get()->reserve(this->_str->length() + 1);
newdata.get()->smartCopy(this->_str);
this->_str = newdata.release();
this->_str->append(c);
}
包装类StringBuffer的
void StringBuffer::reserve(int n) {
if (_length < n) {
int newlength = n; //max(_length*2,n);
char* newbuf = new char[newlength];
//copy contents of the stored string in the new buffer
revSmartCopy(newbuf);
//return stuff from the new buffer to the stored buffer
delete[] this->_strbuf;
this->_strbuf = newbuf;
this->_length = newlength;
newbuf = 0;
}
}
void StringBuffer::revSmartCopy(char* newString) {
int it = 0;
while (it < this->_length) {
newString[it] = this->_strbuf[it];
it++;
}
}
void StringBuffer::smartCopy(StringBuffer* newString) {
int shorterLength = 0;
(this->_length < newString->_length) ? shorterLength = this->_length : shorterLength = newString->_length;
int it = 0;
while (it < shorterLength) {
*_strbuf++ = *(newString->_strbuf)++;
it++;
}
}
此代码正在另一个复制与我们从他们那里追加指向新的副本和旧的一个指向先前
对象的
首先,这不是'C'。其次,'auto_ptr' - 这已被弃用,以支持'std :: unique_ptr'。第三,所有这些代码的目的是什么?在'std :: string'中是否有缺少的东西,你认为你必须实现自己? – PaulMcKenzie
这实际上是一个实现拥有指针并对其执行字符串操作的任务。 – user3585510
追加一个字符并不会把你发布的所有这些东西都拿走。它只需要重新分配,复制,释放,分配。所有这些'StringBuffer'的东西,我不知道它的目的是什么。另外,“*我已经通过浅拷贝将第一个对象复制到了第二个对象中,现在它们都指向同一个位置。” - 因此,如果我在这里接受你所说的,当这些对象被调用析构函数时,会在多次释放指针地址的地方出现双重删除错误。 – PaulMcKenzie