Question

So I am relatively new to C++ and I am having an issue with the following std::vector::const_iterator:

for (vector<shared_ptr<FSNode>>::const_iterator itr = curNode->GetSubNodes().begin() ; itr != curNode->GetSubNodes().end(); itr++)
{
    shared_ptr<FSNode> nextNode = *itr;
    GetXMLFromNode(nextNode, xmlDom, dirEle);
}

The GetSubNodes accessor

const std::vector<shared_ptr<FSNode>> FSNode::GetSubNodes()
{
    return subNodes_;
}

Basically getting a run time error where itr is expected to be a regular iterator. Does anybody know where I am going wrong? Likely a really simple issue but I am not seeing it right now.

Was it helpful?

Solution

GetSubNodes is returning a vector by value. So you get a different copy of the vector every time you call it. The iterator you are getting from this copy is invalid when the copy is destroyed, which happens by the end of the statement. Return the vector by reference instead.

const std::vector<shared_ptr<FSNode>> & FSNode::GetSubNodes()
///////////////////////////////////// ^
{
    return subNodes_;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top