Link to vector :: front works, but vector :: begin does not

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 a little:

clientis that tr1::shared_ptrwhich points to an object that has a member with a name inventorythat has a private element vector<itemPtr>accessible by getMisc(). itemPtris a typedef for tr1::shared_ptr<Item>, and getName()returns a private std::stringmember Item.

Essentially, it client->inventory.getMisc()comes down to std::vector, and I'm trying to get an iterator to its first element.

The problem is that the fourth line is segfaults. Apparently, either the iterator or shared_ptr that it points to is invalid. I used the first cerr instruction to check if the vector itself really is and it prints properly, so I think it is.

Is there something I'm doing wrong? Alternatively, what would you do to debug this?

+3
source share
3 answers

Exactly what is a signature getMisc?

If you really return std::vector<itemPtr>, you return a copy of the list. In this case, the first access pattern will work (slowly), because the temporary copy will not be destroyed until frontit completes execution, and by that time it itemPtrwill be copied to the temporary one. The second fails, because after switching to the iterator c begin, a temporary drop goes out of scope and is destroyed, leaving the just created iterator hanging.

+12
source

, ?

, , , front() (*it).

+1

Are you sure the vector is not empty? It is possible that frontand beginbehave somewhat differently, and frontmay work by accident, while the additional checks of the iterator result in failure when using seg.

0
source

Source: https://habr.com/ru/post/1753919/


All Articles