我有这样的代码块,写成strstream
。我将它转换为sstream
如下。我不确定,但我认为printStream->str()
正在返回一个字符串对象,其中包含printStream
所指向的流缓冲区中的内容的副本(临时),然后您将调用c_str()
并获取const char *
,然后投射该常量,然后将该指针返回到函数作用域之外。我认为,因为您从printStream->str()
得到的临时值,您将使用一个指针来释放此函数之外的内存。我应该怎么做?将strstream转换为关于c_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());
}
不要使用'new',不使用C-风格的转换,不要使用'const_cast' *特别*修改变量,不要使用C风格的字符串,不要返回指向已经释放的内存的指针。事实上,我相当确定,如果重新开始比修复此代码更容易。例如 – milleniumbug
我应该如何更改我的代码?返回const_cast(printStream-> str()。c_str()); –