jjzjj

c++ - 这是违法的吧?

coder 2023-11-13 原文

对于个人项目,我一直在实现自己的 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;
}

在我的版本中,替换是根据我创建的临时字符串实现的,然后用 *this 交换。这显然会使任何迭代器无效。那么我是否正确认为该示例无效?因为它存储迭代器,进行替换然后再次使用迭代器?

我的标准拷贝 (ISO 14882:2003 - 21.3p5) 说:

References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_string object:

- 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().

关于非常量成员函数的条目似乎涵盖了这一点。所以除非我遗漏了什么,否则这段代码使用的是无效的迭代器,对吗?当然,这段代码与 gcc 的 libstdc++ 一起工作得很好,但我们都知道,就标准合规性而言,这并不能证明什么。

最佳答案

如果 replace 就地操作,这似乎会起作用。不过,我认为不需要以这种方式实现。所以是的,我会说您的代码在技术上是非法的。

关于c++ - 这是违法的吧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160882/

有关c++ - 这是违法的吧?的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

  3. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  4. ruby - 如何在 RVM 下将 Bundler 安装到 @global gemset,这是正确的方法吗 - 2

    我在OSX上(如果重要的话)。如果我使用RVM安装Ruby,它会默认将Bundler安装到@globalgemset假设我想要一个不同版本的bundler。我假设我需要做的就是执行geminstallbundler--version但是,这会将bundler安装到默认gemset并且RVM不会为其设置路径。因此,如果我键入bundler,它仍会启动一个与Ruby一起安装到@global中的bundler两个问题:如何将bundler安装到@globalgemset。将bundler安装到@globalgemset中的模式是否正确,或者我遗漏了什么 最佳答案

  5. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  6. c - 这是什么宏? - 2

    在ruby.h中,有很多函数宏是这样定义的:staticinlineint#ifdefined(HAVE_PROTOTYPES)rb_type(VALUEobj)#elserb_type(obj)VALUEobj;#endif{if(FIXNUM_P(obj))returnT_FIXNUM;if(obj==Qnil)returnT_NIL;if(obj==Qfalse)returnT_FALSE;if(obj==Qtrue)returnT_TRUE;if(obj==Qundef)returnT_UNDEF;if(SYMBOL_P(obj))returnT_SYMBOL;returnBU

  7. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  8. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

  9. ruby - 从数组中生成哈希 - 这是如何工作的? - 2

    fruit=["apple","red","banana","yellow"]=>["apple","red","banana","yellow"]Hash[*fruit]=>{"apple"=>"red","banana"=>"yellow"}为什么splat会导致数组被如此整齐地解析为Hash?或者更准确地说,Hash如何“知道”“apple”是键,“red”是其对应的值?仅仅是因为它们在水果数组中的位置是连续的吗?这里使用splat有关系吗?否则哈希不能直接从数组中定义自己吗? 最佳答案 作为documentation状态:H

  10. ruby - Sinatra + Heroku + Datamapper 使用 dm-sqlite-adapter 部署问题 - 2

    出于某种原因,heroku尝试要求dm-sqlite-adapter,即使它应该在这里使用Postgres。请注意,这发生在我打开任何URL时-而不是在gitpush本身期间。我构建了一个默认的Facebook应用程序。gem文件:source:gemcuttergem"foreman"gem"sinatra"gem"mogli"gem"json"gem"httparty"gem"thin"gem"data_mapper"gem"heroku"group:productiondogem"pg"gem"dm-postgres-adapter"endgroup:development,:t

随机推荐