簡體   English   中英

C ++復制構造函數/賦值運算符錯誤

[英]C++ Copy Constructor/Assignment Operator error

我有這些變量:

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> 同樣,出於錯誤原因,有必要查看默認構造函數和析構函數。 從設置的外觀看,您似乎未在默認構造函數中初始化某些成員。 另外,您的賦值運算符有數個資源泄漏,如果您嘗試自賦值,那將是非常糟糕的。 通常,我建議像這樣實現賦值運算符:

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

這利用了為復制構造函數完成的工作,並使用了通常很容易實現的swap()成員。

檢查您的副本構造函數。

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

似乎您可能未正確初始化wordListCapacity_ (很難告訴您,因為您沒有顯示默認的ctor)。 由於它是一個int ,它可以具有負值,當您嘗試wordList_ = new char*[wordListCapacity_];時,這可能會導致段錯誤wordList_ = new char*[wordListCapacity_]; 可能還有其他問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM