2010-11-26 1 views
1

BOOST_FOREACH는 GroupMember 클래스의 멤버로 존재하는 weak_ptr을 무효화합니다. 이유를 이해하도록 도와주세요.BOOST_FOREACH-loop 내부에 설정된 변수가 루프 외부에서 유효하지 않습니다. 이유가 무엇입니까?

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가 구현되어 있다고 가정했는데 이는 잘못된 가정입니다.

둘째, BOOST_FOREACH에서 값순으로 반복합니다. 참조하여보십시오 :

BOOST_FOREACH(EachLevel& aLevel, levels) 

및 작동하는지 확인하십시오.

3

EachLevel aLevel 범위가 BOOST_FOREACH 내에있는 로컬 개체 aLevel을 만듭니다. 이 객체에서 iterator을 가져 오는 경우 루프 외부에서 유효하지 않습니다. EachLevel& aLevel을 선언하여 사본을 만들지 않고 이터레이터가 유효하게 유지되도록 참조로 변경할 수 있습니다. 두 번째 경우에는 복사본을 만들지 않고 개체에 직접 액세스하므로 작동합니다.

+0

아아, 알겠습니다! 추가 된 참조와 함께 작동합니다. – user521048

관련 문제