0

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!

enter image description here

4

1 回答 1

2

可能您的函数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();
     }
于 2013-10-27T11:41:11.747 回答