2017-11-25 5 views
0

이 컨테이너에 대한 가상 클래스 클래스 (요소가 포함되어 있지 않음)와 반복기 클래스를 만들었습니다. 다음 코드는 항상 내 시스템에 '776'을 출력std :: reverse_iterator 이상한 동작 (UB?)

#include <iostream> 
#include <iterator> 

class Container 
{ 
public: 
    class Iterator; 
    Container()=default; 
    Container::Iterator begin(); 
    Container::Iterator end(); 
}; 

class Container::Iterator: public std::iterator<std::bidirectional_iterator_tag, size_t> 
{ 
public: 

    Iterator(size_t n); 
    size_t& operator*(); 
    Container::Iterator& operator--(); 
    const Container::Iterator operator--(int); 

    bool operator==(const Container::Iterator& rhs) const; 
    bool operator!=(const Container::Iterator& rhs) const; 
    private: 
    size_t n_; 
}; 



Container::Iterator Container::end() 
{ 
    return Iterator(777); 
} 





Container::Iterator::Iterator(size_t n): 
    n_(n) 
{ 
} 

size_t& Container::Iterator::operator *() 
{ 
    return n_; 
} 

Container::Iterator& Container::Iterator::operator--() 
{ 
    n_--; 
    return *this; 
} 

const Container::Iterator Container::Iterator::operator--(int) 
{ 
    Container::Iterator oldVal = *this; 
    n_--; 
    return oldVal; 
} 

int main() 
{ 
Container cont; 
std::reverse_iterator<Container::Iterator>revit(cont.end()); 
//as cppreference says, "For a reverse iterator r constructed from an iterator i, the relationship &*r == &*(i-1) is always true...", so I expect that the output must be the same as if I used instead next commented line, and it does so on my system 
    // auto it = cont.end(); it--; std::cout << *it << std::endl; 
    std::cout << *revit << std::endl; 
return 0; 
} 

(내 컴파일러는 GCC 5.4.0입니다)하지만 (C++ 11 지원) 모든 온라인 컴파일러를 사용,이 코드 출력 단지 '0 '(단 하나의 Clang 버전을 제외하고 출력은 일부'임의의 '큰 숫자입니다.)

어디에서 오류가 발생합니까?

Iterator tmp = current; return *--tmp; 

답변

1

std::reverse_iterator::operator*is equivalent to (currentreverse_iterator는 인스턴스에 의해 감싸 기본 반복자 임).

*tmptmp의 구성원에 대한 참조를 반환합니다. 범위를 벗어나 std::reverse_iterator::operator*이 반환되면 해당 구성원을 데려 와서 파괴됩니다. 따라서 *revit은 매달려있는 참조를 반환합니다. 후속 사용 시도는 정의되지 않은 동작을 나타냅니다.