簡體   English   中英

意外的迭代器行為

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM