Reputation: 87
BOOST_FOREACH invalidates a weak_ptr that resides as a member in the class GroupMember, please help me understand why.
The code below explains the error:
class GroupMember
{
bool logInState;
boost::weak_ptr<CUser> wpUser;
};
GroupMember::iterator it;
BOOST_FOREACH(EachLevel aLevel, levels)
{
if(aLevel.exist(spUser))
{
it = aLevel.getIteratorToGroupMember( spUser );
//iterator (it) is valid as well as the group member's attributes (and weak_ptr)
}
}
//Iterator (it) seems to be valid but the weak_ptr is invalid.
//The counter to the object is more than 10 so the weak ptr is not expired.
The code below works perfectly:
GroupMember::iterator it;
std::vector<EachLevel>::iterator itLevel;
for(itLevel = levels.begin(); itLevel != levels.end(); ++itLevel)
{
if(itLevel->exist(spUser))
it = itLevel->getIteratorToGroupMember( spUser );
}
//Here is iterator (it) valid (including the weak_ptr)
I cannot see the difference, can you?
Thanks!
Upvotes: 1
Views: 464
Reputation: 14317
You assumed that BOOST_FOREACH is implemented like in your second code snippet, which is a wrong assumption.
Second, in your BOOST_FOREACH you iterate by value. Try by reference:
BOOST_FOREACH(EachLevel& aLevel, levels)
and see if it works.
Upvotes: 3
Reputation: 73493
EachLevel aLevel
creates a local object aLevel
whose scope is only within the BOOST_FOREACH
. If you take a iterator
from this object it will be invalid outside the loop. You can change it to a reference by declaring EachLevel& aLevel
so that no copy is created and your iterator remains valid. In the second case you are directly accessing the object without creating any copy of it, hence it works.
Upvotes: 3