复制构造函数和getter(mutator函数)出错

时间:2017-11-02 16:56:07

标签: c++ class oop exc-bad-access copy-constructor

所以我创建了一个名为WordFrequency的类,它将字符串字和int频率存储为私有成员变量。 一个HashTable函数,在哈希表中包含WordFrequency **,hashsize,currentitems。

在使用复制构造函数时,我总是收到错误 - 线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x0) 在复制构造函数中调用时,将我重定向到WordFrequency类的getter函数。 我无法弄清楚为什么会这样。

复制构造函数。

Hashtable:: Hashtable(const Hashtable &hash){

    WordFrequency** temp = new WordFrequency* [hash.hashSize];
     this->arr = temp;
    for (int i = 0 ; i < hash.hashSize ; i++) {
        if (hash.arr[i] == NULL){  //pointer in hashstable is null
            continue;
        }
        //bucket is not empty
        if(this->search(this->arr[i]->getWord())   != 0  ){   //if same string already found in this hashtable
            this->arr[i]->increment();    // incrtement the frequency
            continue;
        }

        //else the string doest even exist in the hashtable.

        WordFrequency x ((hash.arr[i])->getWord());   //deep copying the word from the parameter hash
        temp[i] = &x;                               //pointing the hash table to the new the object

    }
    this->hashSize = hash.hashSize;
    this->currentItems = hash.currentItems;
}

wordfrequency类中的getter函数。

string WordFrequency:: getWord()  const {
    return this->word;
}

虽然getter功能看起来很简单但我不知道为什么会出现这个错误。

我也包括我的析构函数,这可能是问题所在。

Hashtable::  ~Hashtable() {
    for (int i = 0 ; i < this->hashSize ; i++){
        delete this->arr[i];
    }
   delete  [] this->arr;
    this->hashSize = 0;
    this->currentItems = 0;

}

输出操作符 -

ostream&  operator<< (ostream &out, const Hashtable &h){
    out << "Hashtable with  size - " << h.hashSize  << "and no of elements - " << h.currentItems << endl;

    for (int i = 0 ; i < h.hashSize ; i++){
        if (h.arr[i] == NULL){
            out << "0";
            continue;
        }
        else {
            out << ((h.arr[i])->getWord());   //bad access
        }
    }


    out << endl;
    return out;

}

1 个答案:

答案 0 :(得分:1)

在HashTable构造函数的for循环中,存储堆栈分配对象的指针:

WordFrequency x ((hash.arr[i])->getWord());
temp[i] = &x; 

该内存在for循环的范围之外被回收,这导致了&#34;糟糕的访问&#34;当您稍后尝试访问该对象时。你应该改为对象:

temp[i] = new WordFrequency((hash.arr[i])->getWord());