[英]Unexpected iterator behavior
在这个循环中,我在svg标记的childs上调用了toString()
方法。 但每次我在第一次迭代中得到Segmentation fault。
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;
}
正如你在这张图片中看到的那样,SVG Tag有子节点,它应该在第一次迭代中调用TagG上的toString()
,但它甚至没有正确设置迭代器,因为TagG有2个子节点,并且解引用迭代器有0孩子和奇怪的属性。 有人能告诉我我的错吗? 谢谢!
可能你的函数getChildren
按值返回然后
std::list<Tag*>::const_iterator it=this->getChildren().begin();
和
it != this->getChildren().end();
指向不同容器的开始和结束 。 从您的编辑中可以看出这正是这种情况,所以请进行更改:
std::list<Tag*>& Tag::getChildren() const{
return children;
}
或者这样做:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.