扩容拷贝问题
源代码使用memcpy拷贝,在使用vector<int>存储内置类型时没有问题,
但是如果存储的是含有指针的类型,如string,就会发生浅拷贝问题
//3、容量相关void reserve(size_t n){if (n > capacity()){size_t old_size = size();T* tmp = new T[n];if (_start)//不为空,拷贝原数据{memcpy(tmp, _start, sizeof(T) * size());delete[] _start;}_start = tmp;_finish = tmp + old_size;//更新_finish_end_of_storage = tmp + n;}}
运行结果
改正代码使用string的赋值重载函数进行拷贝:
void reserve(size_t n){if (n > capacity()){size_t old_size = size();T* tmp = new T[n];//if (_start)//不为空,拷贝原数据仅仅只是(字节拷贝)浅拷贝,有问题//{// memcpy(tmp, _start, sizeof(T) * size());// delete[] _start;//}if (_start){for (size_t i = 0; i < old_size; i++){tmp[i] = _start[i];//使用赋值重载进行拷贝}delete[] _start;}_start = tmp;_finish = tmp + old_size;//更新_finish_end_of_storage = tmp + n;}}