将strstream转换为sstream冲突关于c_str()

Converting strstream to sstream conflict about c_str()

本文关键字:str 转换 strstream sstream 冲突      更新时间:2023-10-16

我有用strstream编写的代码块。我将其转换为sstream如下所示。我不确定,但我认为printStream->str()返回一个字符串对象,其中包含 printStream 指向的流缓冲区中内容的副本(临时),然后您调用它c_str()并得到一个const char *,然后丢弃常量,然后返回函数范围之外的指针。 我认为由于它是您从printStream->str()中获取的临时值,您将使用指向此函数外部已释放内存的指针。我应该怎么做?

char * FieldData::to_string() const
{
  if(printStream)
    return printStream->str();
  FieldData* notConst = (FieldData*) this;
  notConst->printStream = new std::ostrstream;
  // check heap sr60315556
  if (notConst->printStream == NULL)
    return NULL;
  *(notConst->printStream) << "Invalid Field Type";
  *(notConst->printStream) << '';
  return printStream->str();
}
char * FieldData::to_string() const
{
  if(printStream)
    return const_cast<char *>(printStream->str().c_str());
  FieldData* notConst = (FieldData*) this;
  notConst->printStream = new std::ostringstream;
  // check heap sr60315556
  if (notConst->printStream == NULL)
    return NULL;
  *(notConst->printStream) << "Invalid Field Type";
  *(notConst->printStream) << '';
  return const_cast<char *>(printStream->str().c_str());
}

将返回类型更改为 std::string并直接返回std::string对象。

我认为一个名为to_string的函数真的,真的,真的应该返回一个std::string

然后所有这些垃圾都可以被替换为

std::string FieldData::to_string() const
{ return "Invalid Field Type"; }