0
我有一個包含刪除它的功能:功能刪除不要在第二時間的工作,我激活它
void Vector::reserve(int n){
//if there is a need to increase the size of the vector
if (n > _size){
int* tampArr;
//check what the new size of the array should be
_capacity = n + (n - _capacity) % _resizeFactor;
tampArr = new int[_capacity];
//put in the new array the element i have in the curr array
for (int i = 0; i < _size; i++){
tampArr[i] = _elements[i];
}
delete[] _elements;
_elements = NULL;//this
//put the new array in _element
_elements = new int[n];
for (int i = 0; i < _size; i++){
_elements[i] = tampArr[i];
}
delete[] tampArr;
}
}
類領域是:
private:
//Fields
int* _elements;
int _capacity; //Total memory allocated
int _size; //Size of vector to access
int _resizeFactor; // how many cells to add when need to reallocate
首次某種原因,我使用函數它不會顯示任何錯誤並且完美地工作,但在第二次停止時:「delete [] _elements;」它停止。 除了當我運行該功能一次停靠在對象的末尾:
Vector::~Vector(){
delete[] _elements;
}
有人可以幫助我嗎?
確保'_elements'在構造函數中設置爲NULL,否則'reserve'會刪除一些未定義的內存區域。爲了進一步幫助我們,我們需要一個[mcve] –
我希望您知道您的最終_elements數組的大小爲n,而不是_capacity。 –
@AhishekBansal謝謝。我討厭那種錯誤,我的眼睛每次都跳過這條線...... – Holo