【问题标题】:Segmentation Fault with const_iterator while using QT使用 QT 时 const_iterator 的分段错误
【发布时间】:2015-06-17 17:05:18
【问题描述】:

我正在使用 Qt 在 C++ 中开发类似于linkedin 的软件。 当我尝试将用户保存到数据库时遇到问题,特别是当我尝试保存他的联系人时。

调试器说错的函数如下

QString network::getAllContacts(const vector<user*>& d) const{
QString str="";
for(vector<user*>::const_iterator it=friends.begin();it!=friends.end(); ++it){
   for(vector<user*>::const_iterator it2=d.begin(); it2!=d.end(); ++it2){
      if(*it==*it2){
        if(str.size()!=0)
            str=str+","+QString::fromStdString((*it)->getLogin());
        else
            str=QString::fromStdString((*it)->getLogin());
      }
   }
}
return str;
}

它给了我一个分段错误,并显示了 stl vector.h 的行,上面写着

{ return const_iterator(this->_M_impl._M_finish); }

【问题讨论】:

  • 认真思考为什么需要指针向量。它不仅增加了内存管理工作量,而且很少有这是正确的选择。还可以考虑将字符串构建为 std::string 并在最后转换为 QString。

标签: c++ qt vector segmentation-fault


【解决方案1】:

STL 迭代器不能成为函数中的段错误(仅在使用不当的情况下)的原因。您正在取消引用一些未初始化的指针。

在此函数的开头设置断点将使您能够检查“在线”d 及其内容(这是指针!危险就在这里)是否正确。 friends 也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2014-04-10
    • 2013-09-30
    • 2018-04-30
    • 1970-01-01
    相关资源
    最近更新 更多