2010-07-01 62 views
11

因为我一直在执行我自己的libstdC++一个个人项目。一点一滴,我一直在取得一些不错的进展。通常情况下,我会使用示例从http://www.cplusplus.com/reference/一些基本的测试案例,以确保我有明显的功能预期工作。这是违法的权利?

今天,我遇到了一个问题与std::basic_string::replace,特别是使用从网站(http://www.cplusplus.com/reference/string/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来创建一个临时字符串。这显然使任何迭代器无效。那么我是否正确,该示例是无效的?因为它存储迭代器,做一个替换,然后再次使用迭代器?

我的标准的副本(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++来说工作得很好,但是我们都知道,只要符合标准就没有什么证明。

+0

他们需要建立更多的监狱,eep。 – 2010-07-01 19:16:34

+1

如果你想知道这个 - 不要怀疑。 cplusplus.com充满了bug。 – 2010-07-01 19:29:46

回答

2

这似乎工作,如果replace就地操作。我不认为需要这样执行。所以是的,我会说你的代码在技术上是非法的。