簡體   English   中英

為容器類分配額外的內存

[英]allocating extra memory for a container class

嘿,我正在寫一個模板容器類,在過去的幾個小時里,我一直在嘗試為進入容器的額外數據分配新的內存(...撞上一堵磚牆..:|)。

template <typename T>
void Container<T>::insert(T item, int index){
    if ( index < 0){
        cout<<"Invalid location to insert " << index << endl;
        return;
    }


    if (index < sizeC){ 
    //copying original array so that when an item is 
    //placed in the middleeverything else is shifted forward
        T *arryCpy = 0;
        int tmpSize = 0;
        tmpSize = size();
        arryCpy = new T[tmpSize];
        int i = 0, j = 0;
        for ( i = 0; i < tmpSize; i++){
            for ( j = index; j < tmpSize; j++){
                arryCpy[i] = elements[j];
            }
        }
        //overwriting and placing item and location index
        elements[index] = item;
        //copying back everything else after the location at index
        int k = 0, l = 0;
        for ( k =(index+1), l=0; k < sizeC || l < (sizeC-index); k++,l++){
            elements[k] = arryCpy[l];
        }
        delete[] arryCpy;
        arryCpy = 0;
    }

    //seeing if the location is more than the current capacity
    //and hence allocating more memory
    if (index+1 > capacityC){
        int new_capacity = 0;
        int current_size = size();
        new_capacity = ((index+1)-capacityC)+capacityC;
        //variable for new capacity

        T *tmparry2 = 0;
        tmparry2 = new T[new_capacity];
        int n = 0;
        for (n = 0; n < current_size;n++){
            tmparry2[n] = elements[n];
        }
        delete[] elements;
        elements = 0;
        //copying back what we had before
        elements = new T[new_capacity];
        int m = 0;
        for (m = 0; m < current_size; m++){
            elements[m] = tmparry2[m];
        }
            //placing item
        elements[index] = item;
    }

    else{
        elements[index] = item;
    }
    //increasing the current count
    sizeC++;

我的測試條件是Container cnt4(3); 並且當我碰到第四個元素時(當我用於諸如something.insert("random",3); )時,它就會崩潰,並且上述方法不起作用。 我哪里出問題了?

幾件事對我來說沒有太大意義:

if (index+1 > capacityC){

不應該是:

if (index >= capacityC){

另外,當您增加陣列時,我看不到為什么要進行兩次復制。 不應該:

delete[] elements;
elements = 0;

是:

delete[] elements;
elements = tmparray2;

請注意, new T[n]可能不是您在T的容器中實際想要的,因為這已經創建了n個類型為T 對象 您真正想要的是保留內存 ,然后在以后的某個時間點在該內存中構造T類型的對象。

T* data = static_cast<T*>(operator new[](n * sizeof(T));   // allocate memory
// ...
new(&data[size]) T(arguments);   // construct T object in-place
++size;

為了破壞容器,您必須逆轉此過程:逐個破壞對象,然后釋放內存。

while (size) data[--size].~T();   // destruct T object in-place
operator delete[](data);          // release memory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM