2010-07-01 3 views
11

개인 프로젝트의 경우 libstdC++를 자체적으로 구현했습니다. 조금씩, 나는 좋은 발전을 이루었습니다. 일반적으로, 일부 기본 테스트 케이스에 대해 http://www.cplusplus.com/reference/의 예제를 사용하여 예상대로 작동하는 확실한 기능이 있는지 확인합니다.이것은 불법입니다.

오늘은 내가 특별히 (내가 질문의 라인을 지적하는 댓글을 추가 한 ) 사이트 (http://www.cplusplus.com/reference/string/string/replace/)에서 그대로 복사 한 예제를 사용하여 반복자 기반 버전으로, std::basic_string::replace에 문제로 실행 :

// replacing in a string 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string base="this is a test string."; 
    string str2="n example"; 
    string str3="sample phrase"; 
    string str4="useful."; 

    // function versions used in the same order as described above: 

    // Using positions:    *123456789*12345 
    string str=base;    // "this is a test string." 
    str.replace(9,5,str2);   // "this is an example string." 
    str.replace(19,6,str3,7,6);  // "this is an example phrase." 
    str.replace(8,10,"just all",6); // "this is just a phrase." 
    str.replace(8,6,"a short");  // "this is a short phrase." 
    str.replace(22,1,3,'!');  // "this is a short phrase!!!" 

    // Using iterators:     *123456789* 
    string::iterator it = str.begin(); //^
    str.replace(it,str.end()-3,str3); // "sample phrase!!!" 

    // *** this next line and most that follow are illegal right? *** 

    str.replace(it,it+6,"replace it",7); // "replace phrase!!!" 
    it+=8;        //  ^
    str.replace(it,it+6,"is cool");  // "replace is cool!!!" 
    str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!" 
    it+=3;        //   ^
    str.replace(it,str.end(),str4.begin(),str4.end()); 
             // "replace is useful." 
    cout << str << endl; 
    return 0; 
} 

내 교체 버전은 *this으로 교체 한 임시 문자열로 구현됩니다. 이렇게하면 모든 반복기가 명확하게 무효화됩니다. 예제가 유효하지 않다는 것을 알았습니까? iterators를 저장하고, 대체하고 반복자를 다시 사용하기 때문에?

표준의 내 사본 (ISO 14882 : 2003 - 21.3p5)는 말한다 :

참조, 포인터, 반복자

가 다음으로 을 무효화 할 수있는 basic_string 시퀀스의 요소를 참조 그 basic_string 객체의 사용

- As an argument to non-member functions swap() (21.3.7.8), 
    operator>>() (21.3.7.9), and getline() (21.3.7.9). 
- As an argument to basic_string::swap(). 
- Calling data() and c_str() member functions. 
- Calling non-const member functions, except operator[](), at(), 
    begin(), rbegin(), 
    end(), and rend(). 
- Subsequent to any of the above uses except the forms of insert() and 
    erase() which return iterators, 
    the first call to non-const member functions operator[](), at(), begin(), 
    rbegin(), end(), or rend(). 

비 const 멤버 함수에 대한 항목이 포함 보인다. 그래서 뭔가를 놓치지 않으면이 코드는 무효화 된 반복자를 사용하고 있습니까? 물론이 코드는 gcc의 libstdC++에서 잘 작동하지만 표준 준수와 관련해서는 아무것도 증명하지 못했습니다.

+13

사실 이것은 불법이며, 이미 FBI에 알 렸습니다. 좋은 변호사가되기를 바랍니다. –

+0

그들은 더 많은 감옥을 세울 필요가 있습니다. –

+1

궁금한 점이 있으시면 - 궁금하지 마십시오. cplusplus.com에는 많은 버그가 있습니다. –

답변

2

replace이 제자리에서 작동하는 경우 작동하는 것으로 보입니다. 그런 식으로 구현할 필요는 없다고 생각합니다. 그래서 네 코드가 기술적으로 불법이라고 말할 수 있습니다.