2017-05-04 37 views
2
myclass::myclass(queue<queue<char> > construction_info){ 
    //why does this line crash? 
    queue<char> first_line_of_construction_info = construction_info.front(); 
    construction_info.pop(); 
} 

我正在从文本文件(不是由我生成的,所以我不能更改格式)读取到char的队列中。它意味着一行字符。我处理该信息以生成该类。但是,在处理了一些调试消息之后,我意识到第一次执行bad_alloc时(程序在启动时从文本文件初始化所有myclasses)是代码中的这一行。为什么获取导致bad_alloc的char队列队列的前端?

我刚刚与C++合作,我的谷歌福并没有真正帮助我解决这个问题。有没有人有任何建议,我可以开始解决这个崩溃?

简单地取消注释类构造函数就是让我的程序在没有任何崩溃的情况下工作,显然不会产生实际有用的对象。

在linux上使用g ++与C++ 11。

编辑:

这里是主文件的完整代码切:

int initialize_classrooms(){ 
    path p = "files/classrooms/"; 
    //files of lines of queues of chars 
    //vector of vector of queue of char 
    vector<queue<queue<char> > > classroom_files; 
    if(exists(p)){ 
    for (directory_entry& x : directory_iterator(p)){ 
     queue<queue<char> > cur_file; 

     ifstream file(x.path().filename().string()); 

     queue<char> cur_line; 
     char ch; 
     while (file >> noskipws >> ch) { 
     if(!isspace(ch)){ 
      cur_line.push(ch); 
     }else if(ch == '\n'){ 
      cur_file.push(cur_line); 
      cur_line = queue<char>(); 
     } 
     } 
     classroom_files.push_back(cur_file); 
     cur_file = queue<queue<char> >(); 
     file.close(); 
    } 
    }else{ 
    cout << "Classroom files are missing!" << endl; 
    return 1; 
    } 
    cout << "Got all the way to classroom creation" << endl; 
    int i = 1; 
    for(auto cf : classroom_files){ 
    cout << "Number of loops: " << i << endl; 
    i++; 
    shared_ptr<classroom> cr = shared_ptr<classroom>(new classroom(cf)); 
    } 
    cout << "Got past the classroom creation" << endl; 
    return 0; 
} 
+1

排队有多大? bad_alloc通常意味着你的内存不足。 –

+0

你怎么知道队列中有东西?在尝试获取物品之前,您能够获得队列的大小吗? –

+0

@PaulRooney我已经添加了代码 –

回答

0

如果目标仅仅是的内容(在前面的队列),然后创建(恒定)参考是优选的。

queue<char> const& first_line_of_construction_info = construction_info.front(); 
      ^^^^^^ 

后 “读” ING,它可以pop ED就像在当前的代码。

编辑:(谢谢@Remy Lebeau) 因为副本是浪费,myclass构造函数可以通过引用而不是值的construction_info

myclass::myclass(queue<queue<char> > const& construction_info) { 
            ^^^^^^ 

查看代码的其余部分,你可能不希望这些队列队列的多个副本浮动。

另外:除非另有限制,否则不要使用queue<char>来存储一行文本,请考虑使用std::string

+0

我假设我的代码正在创建front()的副本。现在用你的答案,我明白const引用是如何工作的。但是,您是否也可以告诉我如何创建副本,以便我可以看到差异。 –

+1

'myclass'构造函数也应该通过引用而不是按值来使用'construction_info',以便它实际上是在原始'队列'而不是副本上进行操作。 –

+0

@RemyLebeau是因为复制它只是浪费,还是你建议因为其他问题? –