简体   繁体   中英

Unexpected iterator behavior

In this loop I call toString() method on svg tag's childs. But every time I get Segmentation fault in the first iteration.

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. Could someone show me what I got wrong? Thanks!

在此输入图像描述

probably your function getChildren returns by value and then

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();
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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