简体   繁体   English

意外的迭代器行为

[英]Unexpected iterator behavior

In this loop I call toString() method on svg tag's childs. 在这个循环中,我在svg标记的childs上调用了toString()方法。 But every time I get Segmentation fault in the first iteration. 但每次我在第一次迭代中得到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;
}

As you can see in this image, SVG Tag has childs, it should call toString() on TagG in first iteration, but it doesn't even set iterator correctly as you can see, because TagG has 2 childs and that dereferenced iterator has 0 childs and weird attributes. 正如你在这张图片中看到的那样,SVG Tag有子节点,它应该在第一次迭代中调用TagG上的toString() ,但它甚至没有正确设置迭代器,因为TagG有2个子节点,并且解引用迭代器有0孩子和奇怪的属性。 Could someone show me what I got wrong? 有人能告诉我我的错吗? Thanks! 谢谢!

在此输入图像描述

probably your function getChildren returns by value and then 可能你的函数getChildren按值返回然后

std::list<Tag*>::const_iterator it=this->getChildren().begin();

and

it != this->getChildren().end();

points to the begin and the end of different containers. 指向不同容器开始结束 From your edit it is clear this is exactly this case, so please do a change: 从您的编辑中可以看出这正是这种情况,所以请进行更改:

std::list<Tag*>& Tag::getChildren() const{
     return children;
}

or do it like: 或者这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM