This is one weird behavior that I don’t understand I have.
I have a class a with a list, and a getter on it :
class A
{
private:
std::list<OtherClass *> l;
public:
std::list<OtherClass *> getL()
{
return l;
}
}
Then, if I do something like :
A inst;
std::list<OtherClass *>::iterator itB = inst.getL().begin();
std::list<OtherClass *>::iterator itE = inst.getL().end();
for (; itB != itE; ++itB) // Instant ABORT !
But if I do :
A inst;
std::list<OtherClass *> l = inst.getL();
std::list<OtherClass *>::iterator itB = l.begin();
std::list<OtherClass *>::iterator itE = l.end();
for (; itB != itE; ++itB) // It works now !
Can somebody explain to me why is this happening please ? Why have I to go through a temporary variable like this to not abort ?
Thank you in advance !
Change your getter to return a reference to the underlying list.
Without an ampersand it returns a copy of the list each time you call it. Consequently,
itBanditEend up being iterators from different lists. And if that’s not bad enough, those two lists are temporaries which will have been destroyed by the time theforloop begins!To match this if you use
lyou should make it a reference variable, too.