给定迭代器时std :: string :: erase()段错误

时间:2017-06-01 07:39:25

标签: c++11 stl

我有一个字符串 -

std::string out;

和该字符串上的迭代器 -

std::string::iterator pos = out.begin();

如果我这样做 -

if(!out.empty() || pos > out.begin())
  out.erase(pos--);

这是一个错误的段错误 -

Program received signal SIGSEGV, Segmentation fault.
            __memmove_ssse3 () at ../sysdeps/x86_64/multiarch/memcpy-ssse3.S:2821
2821    ../sysdeps/x86_64/multiarch/memcpy-ssse3.S: No such file or directory.

我错过了什么?

对于某些上下文,我使用ncurses实现行编辑,此代码定义了按下退格时的行为。

修改

即使我将减量移出呼叫之后也会出现段错误。

这是一个MCVE -

#include <string>
#include <ncurses.h>

int main()
{

  initscr();
  cbreak();
  keypad(stdscr, true);                           //Seems to be causing the error
  std::string out;
  std::string::iterator pos = out.begin();
  short ch;
  bool insert = false;
  int y, x;

  while(true)
  {
    ch = getch();                                 //Get next character

    if(ch == '\n')
      break;                                      //End of line

    else if(ch == KEY_BACKSPACE)                  //Backspace behaviour defined here
    {
      if(!out.empty())
      {
        out.erase(pos);                           //Character erased from string as per backspace
        addch('\b');                              //Erasure reflected on screen
        std::string temp(pos, out.end());         //
        getyx(stdscr, y, x);
        mvaddstr(y, x - 1, temp.c_str());
      }
    }

    else if(std::isalnum(ch) || std::ispunct(ch)) //Normal characters
    {
      if(!insert)                                 //If insert is off
        out.insert(pos++, ch);                    //Character inserted normally
      else                                        //Insert is on
      {
        *pos = ch;                                //Overwrite characters
        pos++;
      }
    }
  }
  endwin();
  return 0;
}

使用

进行编译
g++ -lncurses -std=c++11 

-Wall没有提供任何线索。

1 个答案:

答案 0 :(得分:1)

这是std :: string的预期行为。在C ++标准中,字符串迭代器的有效性在修改字符串后没有保证,与其他具有更强要求的类型相反。

在[string.require](§21.4.1)中,标准声明:

  

引用a的元素的引用,指针和迭代器   basic_string序列可能会被以下用途无效   basic_string对象:[...]调用非const成员函数,   除了operator [],at,data,front,back,begin,rbegin,end和   雷德。