C ++ Copy Constructor / Assignment Operator错误

时间:2012-02-09 00:15:14

标签: c++ copy segmentation-fault copy-constructor assignment-operator

我有这些变量:

char** wordList_;
int wordListCapacity_;
int* wordCountList_;
char* fileName_;
int nUniqueWords_;
int nTotalWords_;
int nTotalCharacters_;

我的副本构造函数:

FileIndex::FileIndex(const FileIndex& fi)
{
    fileName_ = new char[strlen(fi.fileName_) + 1];
    strcpy(fileName_, fi.fileName_);
    cout << "Jiasd?" << endl;
    wordListCapacity_ = fi.wordListCapacity_;
    nUniqueWords_ = fi.nUniqueWords_;
    nTotalWords_ = fi.nTotalWords_;
    nTotalCharacters_ = fi.nTotalCharacters_;

    wordList_ = new char*[wordListCapacity_];
    wordCountList_ = new int[wordListCapacity_];
    for(int i = 0; i < nUniqueWords_; i++) {
        wordList_[i] = fi.wordList_[i];
        wordCountList_[i] = fi.wordCountList_[i];
    }
}

我重载的赋值运算符:

FileIndex& FileIndex::operator=(const FileIndex& fi)
{
    fileName_ = new char[strlen(fi.fileName_) + 1];
    strcpy(fileName_, fi.fileName_);
    wordListCapacity_ = fi.wordListCapacity_;
    nUniqueWords_ = fi.nUniqueWords_;
    nTotalWords_ = fi.nUniqueWords_;
    nTotalCharacters_ = fi.nTotalCharacters_;
    wordList_ = new char*[wordListCapacity_];
    wordCountList_ = new int[wordListCapacity_];
    for (int i = 0; i < nUniqueWords_; i++) {
        wordList_[i] = new char[strlen(fi.wordList_[i])+1];
        strcpy(wordList_[i], fi.wordList_[i]);
        wordCountList_[i] = fi.wordCountList_[i];
    }
    return *this;
}

每当我创建一个FileIndex(称为FirstIndex)并使用有意义的东西(非NULL)初始化成员变量时,我会使用这些行来测试复制构造函数和赋值运算符:

FileIndex secondIndex = firstIndex;
FileIndex thirdIndex;
secondIndex = thirdIndex; // Segmentation fault here

我使用赋值运算符得到了分段错误,但我感觉可能是因为复制构造函数中的代码错误。话虽这么说,如果复制构造函数中有错误,那么在赋值运算符中也可能存在错误。

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

我认为你想为你的班级使用std::stringstd::vector<T>。此外,出于出错的目的,有必要查看默认构造函数和析构函数。从您设置的外观看来,您可能会例如没有初始化默认构造函数中的一些成员。此外,您的赋值运算符有几个资源泄漏,如果您尝试自我分配将非常糟糕。一般来说,我建议实现这样的赋值运算符:

T& T::operator= (T other) {
    other.swap(*this);
    return *this;
}

这利用了复制构造函数所做的工作,并使用swap()成员,这通常很容易做到。

答案 1 :(得分:1)

查看你的复制构造函数。

for(int i = 0; i < nUniqueWords_; i++) {
    wordList_[i] = fi.wordList_[i];
    wordCountList_[i] = fi.wordCountList_[i];
}

问题在于wordList_[i] = fi.wordList_[i];。您没有像在赋值运算符中那样分配新内存和执行strcpy。相反,您的新副本实际上指向它正在复制的实例中的数据。我相信这可能是David Schwartz所暗示的。

答案 2 :(得分:0)

看起来您可能无法正确初始化wordListCapacity_(因为您没有显示默认的ctor,所以很难说)。由于它是int,因此它可能具有负值,这会在您尝试wordList_ = new char*[wordListCapacity_];时导致段错误。可能还有其他问题。