Converting strstream to sstream conflict about c_s

2019-03-05 05:50发布

I have this code block as written with strstream. And I converted it to sstream as below. I'm not sure, but I think printStream->str() is returning a string object with a copy (temporary) of the contents in the stream buffer pointed by printStream, and then then you are invoking c_str() on it and getting a const char *, and then casting away the const-ness, and then returning the pointer outside the function scope. I think since its a temporary value you are getting back from printStream->str(), you will be using a pointer to deallocated memory outside this function. How should I do this?

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());
}

2条回答
该账号已被封号
2楼-- · 2019-03-05 05:53

I think a function called to_string really, really, really should return a std::string.

And then all this junk can be replaced by

std::string FieldData::to_string() const
{ return "Invalid Field Type"; }
查看更多
beautiful°
3楼-- · 2019-03-05 05:59

Change the return type to std::string and return a std::string object directly.

查看更多
登录 后发表回答