2010-11-26 10 views
1

BOOST_FOREACHは、GroupMemberクラスのメンバーとして存在するweak_ptrを無効にします。理由を理解するのを助けてください。BOOST_FOREACHループ内の変数セットがループ外で無効です、なぜですか?

以下のコードは、エラーを説明する:

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) 

私は違いを見ることができない、できますか?

ありがとうございます!

答えて

3

BOOST_FOREACHが2番目のコードスニペットのように実装されていると仮定しましたが、これは間違った前提です。

第2に、あなたのBOOST_FOREACHでは値で繰り返されます。参考までにお試しください:

BOOST_FOREACH(EachLevel& aLevel, levels) 

3

EachLevel aLevelは、範囲がBOOST_FOREACHの範囲内にあるローカルオブジェクトaLevelを作成します。このオブジェクトからiteratorを受け取った場合、ループ外では無効になります。 EachLevel& aLevelを宣言してコピーを作成せず、イテレーターが有効なままになるように、参照に変更することができます。後者の場合は、オブジェクトのコピーを作成せずにオブジェクトに直接アクセスしているため、動作します。

+0

ああ、わかります!それは追加された参照で動作します。 – user521048

関連する問題