I have this bit of code:
cerr << client->inventory.getMisc().front()->getName() << endl;
vector<itemPtr>::iterator it;
it = client->inventory.getMisc().begin();
cerr << (*it)->getName() << endl;
Let me explain that a bit:
client is a tr1::shared_ptr that points to an object that has a member named inventory that has a private vector<itemPtr> member accessible by getMisc(). itemPtr is a typedef for tr1::shared_ptr<Item>, and getName() returns a private std::string member of Item.
Essentially, client->inventory.getMisc() boils down to a std::vector, and I’m trying to get an iterator to its first element.
The problem is that the fourth line segfaults. Apparently either the iterator or the shared_ptr it points to is invalid. I used the first cerr statement to test if the vector itself was valid, and it prints as it should, so I think it is.
Is there anything I’m doing wrong? Alternatively, what would you guys do to debug this?
Exactly what is the signature of
getMisc?If you’re actually returning a
std::vector<itemPtr>then you are returning a copy of the list. In that case, the first access pattern will work (slowly) because the temporary copy doesn’t get destroyed until afterfrontfinishes executing, by which time theitemPtritself is copied into a temporary. The second fails because after getting at the iterator withbegin, the temporary falls out of scope and is destroyed, leaving the just-created iterator hanging.