0

我有这个代码块,用strstream. 我将其转换sstream为如下。我不确定,但我认为printStream->str()返回一个字符串对象,其中包含 指向的流缓冲区中的内容的副本(临时),printStream然后您调用c_str()它并获取 a const char *,然后丢弃 const-ness ,然后返回函数范围之外的指针。我认为由于它是一个临时值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) << '\0';
  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) << '\0';
  return const_cast<char *>(printStream->str().c_str());
}
4

2 回答 2

1

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

于 2017-10-20T09:53:26.130 回答
1

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

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

std::string FieldData::to_string() const
{ return "Invalid Field Type"; }
于 2017-10-20T10:27:27.433 回答