为什么在通过引用传递对象时不断出现分段错误?

时间:2014-02-17 23:39:35

标签: c++ segmentation-fault

我正在尝试从文件中获取数据并将其存储在我创建的对象中。我一直遇到分段错误,但我不确定是什么导致它。这是代码:

Object<string> populateObj(Object<string>&,string);
string clean(string);
int main(){
  string dictionaryFile;
  ifstream inFile;
  ofstream outFile;
  Object<string> obj1;
  cout << "Enter the name of the Dictionary file" << endl;
  cin >> dictionaryFile;
  obj1 = populateObj(obj1,dictionaryFile);
}
Object<string> populateObj(Object<string> &obj,string fileName){
  ifstream file;
  string words = "";
  file.open(fileName);
  if(file.is_open()){
    while(!file.eof()){
      file >> words;
      obj.add(words);
    }
  }
  else
    cout << "could not open file..." << endl;
  return obj;
}

3 个答案:

答案 0 :(得分:3)

这可能会也可能不会导致您的问题,但这是错误的:

if(file.is_open()){
    while(!file.eof()){
        file >> words;
        obj.add(words);
    }
}

尝试改为:

while (file >> words) {
  obj.add(words);
}

您的原始代码太早测试EOF无法使用。

答案 1 :(得分:1)

int main(){
  //...
  Object<string> obj1;
  //...
  obj1 = populateObj(obj1,dictionaryFile);
}
Object<string> populateObj(Object<string> &obj,string fileName){
  //...
      obj.add(words);
  //...
  return obj;
}

你不必要地覆盖了这个对象。不要这样做。虽然从技术上说它可以工作,但这是一个坏习惯(它指向你的复制操作员有一个错误)。

相反,返回引用(如果有的话)并且不要覆盖该对象。另外,不要按值传递字典字符串,通过const引用传递它:

int main(){
  //...
  Object<string> obj1;
  //...
  populateObj(obj1,dictionaryFile);
}
Object<string>& populateObj(Object<string> &obj,const string& fileName){
  //...
      obj.add(words);
  //...
  return obj;
}

答案 2 :(得分:1)

我希望问题出在您的Object类中。如果保留现有代码并定义这样的对象,那么它运行时没有错误:

template<class T> class Object {
public:
    void add(T);
};

template <class T> void Object<T>::add(T val)
{
    cout << "Adding " << val << "\n";
}

因此,您需要查看您的Object类以了解它失败的原因。最可能的位置是复制对象以返回它,然后复制回原始obj1。该类是否分配内存,或使用不可复制的成员变量?

如果你拿出不必要的对象返回,你可以通过避免复制来“修复”问题,但是你可能仍然想要修复对象,否则这个问题可能会在对象得到的时候浮出水面。复制。

相关问题