C++ 复制构造函数/赋值运算符错误

标签 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

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

在此先感谢您的帮助!

最佳答案

我想你想使用 std::stringstd::vector<T>为你的类(class)。此外,为了了解出错的原因,有必要查看默认构造函数和析构函数。从你的设置来看,你似乎可以,例如没有在默认构造函数中初始化一些成员。另外,你的赋值运算符有几个资源泄漏,如果你尝试 self 赋值,结果会很糟糕。一般来说,我建议像这样实现赋值运算符:

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

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

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

相关文章:

c++ - 我是否需要删除使用 new 和 placement 构造的对象

c++ - 使用 glOrtho() 时 gluLookAt() 不起作用?

c++ - 二叉搜索树 - 将一棵树复制到另一棵树

c++ 数组拷贝显示 vc++ 中的错误

将三个数组复制到 C 中的 2 个暗数组

copy - Lotus Notes 7 - 复制/移动文档。 (父级和响应文档)不更改 UNID?

c - 段错误,C 中的列表

c++ - Dllmain 可以使用 FreeLibrary 吗?

c - 来自命令行参数的段错误(核心转储)

c - 如何正确动态分配内存?