【发布时间】:2017-10-20 09:27:35
【问题描述】:
我有这个用strstream 编写的代码块。我将其转换为sstream,如下所示。我不确定,但我认为printStream->str() 正在返回一个字符串对象,其中包含printStream 指向的流缓冲区中内容的副本(临时),然后您在其上调用c_str() 并获得一个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());
}
【问题讨论】:
-
不要使用
new,不要使用C风格的强制转换,不要使用const_cast尤其是来修改变量,不要使用C -style 字符串,不要返回指向已释放内存的指针。事实上,我很确定重新开始是否比修复此代码更容易。 -
例如我应该如何更改我的代码? return const_cast
(printStream->str().c_str());
标签: c++ compiler-errors sstream c-str strstream