Converting strstream to sstream conflict about c_str()

蹲街弑〆低调 提交于 2019-12-04 06:02:08

问题


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


来源:https://stackoverflow.com/questions/46846162/converting-strstream-to-sstream-conflict-about-c-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!