C++ 意外迭代器行为

C++ 意外迭代器行为,c++,iterator,segmentation-fault,C++,Iterator,Segmentation Fault,在这个循环中,我对svg标记的child调用toString()方法。但每次我在第一次迭代中遇到分段错误 std::list<Tag*> children; std::string TagSvg::toString() const{ if(this->getChildren().empty()) return "<svg/>"; std::string temp=""; temp+="<svg>\n"; fo

在这个循环中,我对svg标记的child调用
toString()
方法。但每次我在第一次迭代中遇到分段错误

std::list<Tag*> children;

std::string TagSvg::toString() const{
     if(this->getChildren().empty()) return "<svg/>";

     std::string temp="";
     temp+="<svg>\n";

     for(std::list<Tag*>::const_iterator it=this->getChildren().begin(); it != this->getChildren().end(); ++it){
          temp+=(*it)->toString();
     }

     temp+="</svg>\n";

     return temp;
}


std::list<Tag*> Tag::getChildren() const{
     return children;
}
std::列出子项;
std::string TagSvg::toString()常量{
如果(this->getChildren().empty())返回“”;
std::string temp=“”;
温度+=“\n”;
对于(std::list::const_迭代器it=this->getChildren().begin();it!=this->getChildren().end();+it){
temp+=(*it)->toString();
}
温度+=“\n”;
返回温度;
}
std::list标记::getChildren()常量{
返回儿童;
}
如图所示,SVG标记有child,它应该在第一次迭代中调用TagG上的
toString()
,但它甚至没有像您所看到的那样正确设置迭代器,因为TagG有2个child,而取消引用的迭代器有0个child和奇怪的属性。有人能告诉我我做错了什么吗?谢谢


可能您的函数
getChildren
按值返回,然后

std::list<Tag*>::const_iterator it=this->getChildren().begin();
指向不同容器的开始结束从您的编辑中可以清楚地看出这正是这种情况,因此请进行更改:

std::list<Tag*>& Tag::getChildren() const{
     return children;
}
std::list&Tag::getChildren()常量{
返回儿童;
}
或者像:

std::list<Tag*> children = this->getChildren(); //now you ensure you work on
                                                //a single and the same container
for(std::list<Tag*>::const_iterator it=children.begin();
                                         it != this->children.end(); ++it){
          temp+=(*it)->toString();
     }
std::list children=this->getChildren()//现在你要确保你的工作
//同一容器
对于(std::list::const_迭代器it=children.begin();
它!=这个->子对象.end();++它){
temp+=(*it)->toString();
}

请粘贴函数getChildren的代码。它是按值返回的吗?你能试着把这个“temp+=(*it)->toString();”改成“temp+=it->toString();”这个吗?
std::list<Tag*> children = this->getChildren(); //now you ensure you work on
                                                //a single and the same container
for(std::list<Tag*>::const_iterator it=children.begin();
                                         it != this->children.end(); ++it){
          temp+=(*it)->toString();
     }