我有这些变量:

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

我在赋值运算符中遇到了段错误,但我感觉可能是由于复制构造函数中的代码错误。就是说,如果复制构造函数中有错误,则赋值运算符中也可能有一个错误。

先谢谢您的帮助!

最佳答案

检查您的副本构造函数。

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提到的。

关于c++ - C++复制构造函数/赋值运算符错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9203668/

10-11 18:55