Converting strstream to sstream conflict about c_s

2019-03-05 06:06发布

问题:

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

回答1:

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



回答2:

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"; }