1

我有这些变量:C++拷贝构造函数/赋值运算错误

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)并用意思初始化成员变量gful(NOT NULL)我有这些线测试拷贝构造函数和赋值操作符:

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

我与赋值运算符分段错误,但我有一种感觉,可能是因为拷贝构造函数故障代码。也就是说,如果复制构造函数中有错误,那么在赋值运算符中也可能有一个错误。

在此先感谢您的帮助!

+0

简化课程会发生什么? – Beta 2012-02-09 00:17:43

+0

你的析构函数是什么样的? – 2012-02-09 00:17:45

+0

改为使用'std :: vector',你的问题可能会消失。还要了解* ctor-initializer *列表。 – 2012-02-09 00:18:39

回答

1

检查出你的拷贝构造函数。

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

问题是与wordList_[i] = fi.wordList_[i];。您不像在赋值运算符中那样分配新内存并在此执行strcpy。相反,您的新副本实际上是指向正在复制的实例中的数据。我相信这可能是大卫施瓦茨所暗指的。

2

我想你想为你的班级使用std::stringstd::vector<T>。另外,出于错误的目的,有必要查看默认的构造函数和析构函数。从你的设置看,你似乎可以没有初始化默认构造函数中的某些成员。此外,你赋值运算符有几个资源泄漏,如果你尝试自我赋值,那么将会非常糟糕。在一般情况下,我建议实行赋值运算符是这样的:

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

这对于充分利用拷贝构造函数所做的工作,并使用swap()成员通常是很容易做到的。

0

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