复制阵列和清理

时间:2013-10-29 12:33:01

标签: c++ arrays

我正在尝试将我的数组复制到一个更大的数组中,然后删除旧数组以清理它们。该类有一个int和一个指针,并覆盖析构函数以确保它可以在我delete []时不删除指针。但我在delete []上抛出异常。我使用= new field[1000];初始化数组。

我得到"Collections.exe has triggered a breakpoint.",但断点不是我的。

inline void _resize(unsigned int newTableSize, bool _trimCalled){ 
            if (newTableSize < tableSize && _trimCalled == false) {
                _trim();
                return; 
            }
            field* newTable = new field[newTableSize]; 
            for (unsigned int x = 0; x < newTableSize; x++)
                newTable[x] = table[x];
            tableSize = newTableSize;  
            delete[] table;
            table = newTable;   

    }
inline void _trim(){
    // compact the table 
    // fill in from the end of the table
    for (int x = tableSize; !emptyPlaces.empty() ; x--){
        if (table[x].used = true){
            table[emptyPlaces.top()] = table[x];
            emptyPlaces.pop();
        }
    }
    // trim the excess
    _resize((unsigned int)(usedFields * 1.1 + 10), true);


template<typename key, typename object> class DictonaryArray {
    struct field{
        field(){ this->key = 0; this->_object = nullptr; this->used = false; }
        field(key _key, object __object){;
            key = _key;
            _object = new object();
            *_object = __object;
            this->used = true;
        }
        ~field(){ 
        }
        key key;
        object* _object;
        bool used;
    };

1 个答案:

答案 0 :(得分:1)

table = newtable;; 
delete[] table;

看起来很可疑。

也许你想要,

delete[] table;
table = newTable; 

删除旧表并为其分配新表的地址。

修改1:

另外, 假设tableSize是旧表的大小

for (unsigned int x = 0; x < newTableSize; x++)

需要

for (unsigned int x = 0; x < tableSize; x++)

因为table[x]只能读到tableSize-1