【发布时间】:2012-03-01 11:58:35
【问题描述】:
我有这些变量:
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::vector,您的问题可能会消失。还可以了解 ctor-initializer 列表。 -
nTotalWords_ = fi.nUniqueWords_;在赋值运算符中应该是nTotalWords_ = fi.nTotalWords_;,但我认为这不会导致您发布的代码出现任何问题。你试过运行 valgrind 吗? -
请使用 std::string 和 std::vector 这段代码的所有问题都会消失。 PS。复制和交换成语是你的朋友。
标签: c++ copy segmentation-fault copy-constructor assignment-operator