BOOST_FOREACH使作为GroupMember类成员的weak_ptr无效,请帮助我理解原因。
以下代码说明了该错误:
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.
下面的代码运行完美:
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)
我看不出区别,可以吗?
谢谢!
最佳答案
您假设BOOST_FOREACH的实现方式与您的第二段代码一样,这是一个错误的假设。
其次,在您的BOOST_FOREACH中,按值进行迭代。通过引用尝试:
BOOST_FOREACH(EachLevel& aLevel, levels)
看看是否可行。
关于c++ - 在BOOST_FOREACH循环内设置的变量在循环外无效,为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4283435/