这是非法的吗?

Eva*_*ran 11 c++ string iterator

对于个人项目,我一直在实现自己的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:                 0123456789*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:                      0123456789*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;
}
Run Code Online (Sandbox Code Playgroud)

在我的版本的替换是根据我创建然后交换的临时字符串实现的*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().
Run Code Online (Sandbox Code Playgroud)

关于非const成员函数的条目似乎涵盖了这一点.所以,除非我遗漏了一些东西,否则这段代码使用的是无效的迭代器吧?当然这个代码在gcc的libstdc ++中运行得很好,但是我们都知道,就标准兼容性而言,没有任何证据.

Mic*_*fik 2

replace如果就地操作,这似乎是有效的。但我认为不需要以这种方式实施。所以是的,我想说你的代码在技术上是非法的。