我有这个代码块,用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());
}